Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Error 22031: Fix Invalid JSON Datetime

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

PostgreSQL error 22031 means you passed a value to a JSON datetime function that it cannot interpret as a valid timestamp. The fix is to make sure the string you feed to to_json(), jsonb_set(), jsonb_build_object() or a ::json cast is either a real timestamp/date type or an ISO 8601 string that matches your session's DateStyle. In practice, about nine out of ten occurrences come from one of three things: a date string in the wrong order (for example 03/04/2024 when the server expects 2024-03-04), a NULL or empty string being cast, or a time zone offset that does not match the column type. Work through the steps below in order; the first two will fix most cases.

What You'll Need

  • Access to a PostgreSQL client (psql, pgAdmin, DBeaver, or your application's database console) with permission to run SELECT and SHOW.
  • The exact SQL statement that triggers the error, plus the value being passed to the JSON function.
  • Knowledge of the server's DateStyle and TimeZone settings (you will read these in step 1).
  • A test database or a transaction you can roll back, so you can experiment without changing production data.

Step-by-Step

  1. Reproduce the error in isolation. Copy the failing statement into psql and run it inside a transaction: BEGIN; then your statement, then ROLLBACK;. If the error only appears when a variable is bound (for example from a Python or Node driver), replace the placeholder with a literal value and run it again. This tells you whether the problem is the SQL itself or the value the driver is sending.
  2. Check the server's date settings. Run SHOW DateStyle; and SHOW TimeZone;. A DateStyle of ISO, MDY means 03/04/2024 is read as March 4; ISO, DMY reads it as April 3. If your application sends ambiguous slash-separated dates, this mismatch alone produces 22031. Note the values so you can compare them with what your code sends.
  3. Inspect the actual value being passed. In psql, run SELECT pg_typeof(your_value), your_value; on the expression that feeds the JSON function. Look for text, unknown or NULL. If the type is text and the content is an empty string or a placeholder like '0000-00-00', that is your cause: PostgreSQL cannot convert it to a timestamp, so the JSON function raises 22031.
  4. Convert to a real timestamp before building JSON. Instead of to_json('2024-03-04'::text), cast explicitly: to_json('2024-03-04'::timestamp) or to_json(to_timestamp('2024-03-04 10:00', 'YYYY-MM-DD HH24:MI')). For jsonb, jsonb_build_object('created_at', '2024-03-04'::timestamptz) works because the cast happens before the JSON constructor sees the value. Always cast to the exact type the column expects (date, timestamp or timestamptz).
  5. Use ISO 8601 in string literals. If you must pass a string, write it as 2024-03-04T10:00:00Z or 2024-03-04 10:00:00+00. ISO 8601 is unambiguous regardless of DateStyle, so it survives changes to server configuration and migrations between environments. Avoid MM/DD/YYYY and DD/MM/YYYY entirely in code that builds JSON.
  6. Handle NULLs explicitly. A NULL passed to to_json() is fine (it becomes JSON null), but a NULL cast to timestamp inside jsonb_set() or a || concatenation can trigger 22031. Wrap the value with COALESCE(your_value::timestamp, now()) or filter rows with WHERE your_value IS NOT NULL before the JSON step. Decide deliberately whether a missing date should become JSON null or a default.
  7. Fix time zone mismatches. If the target column is timestamp without time zone but you pass a string ending in Z or +02:00, PostgreSQL will try to strip the offset using the session TimeZone. That usually works, but it fails when the offset is malformed (for example +2 instead of +02:00). Normalise offsets to two digits with a colon, or cast to timestamptz and let PostgreSQL convert.
  8. Validate in the application layer. Before the query runs, parse the date in your language (Python datetime.fromisoformat, JavaScript new Date() with an explicit format check, Java LocalDateTime.parse). Reject or repair bad values there rather than relying on PostgreSQL to guess. This prevents 22031 from reaching the database at all and gives you a clearer error message for the user.
  9. Test the corrected statement. Run it inside a transaction again, then SELECT the resulting JSON to confirm the date appears as expected. Check both a normal value and an edge case (midnight, a leap day, a value near a time zone boundary). Only then commit and deploy the change.

Common Mistakes

  • Assuming the error is about JSON syntax. 22031 is a datetime conversion failure, not a malformed JSON document. The JSON part of the statement is usually fine; the value going into it is not.
  • Relying on implicit casts. PostgreSQL will cast text to timestamp in many contexts, but the rules depend on DateStyle and the exact string. Explicit casts remove the guesswork.
  • Passing the driver's default date format. Some drivers serialise dates as Mon Mar 04 2024 or as epoch milliseconds. Neither is a valid PostgreSQL timestamp literal. Convert to ISO 8601 in the driver or use a parameterised query with a real timestamp parameter.
  • Ignoring empty strings. '' is not a valid timestamp and is not the same as NULL. Treat empty strings as missing data and convert them before the JSON step.
  • Changing DateStyle globally to "fix" it. That masks the bug and breaks other queries. Fix the value, not the server setting.

Tips

  • Prefer jsonb over json for new columns: it validates on input and gives clearer errors, and it supports indexing.
  • Use to_char(your_timestamp, 'YYYY-MM-DD"T"HH24:MI:SSOF') when you need a stable ISO string for output, rather than relying on the default text representation.
  • Keep a small test table with edge-case dates (leap day, month end, DST transition) and run your JSON-building queries against it after any PostgreSQL upgrade.
  • Log the raw value alongside the SQL error in your application so you can see exactly what was sent, not just what the database reported.

Troubleshooting

If the error persists after casting explicitly, check whether the value contains hidden characters such as a trailing space, a non-breaking space or a Unicode dash instead of a hyphen. Copy the value into a hex viewer or run SELECT encode(convert_to(your_value, 'UTF8'), 'hex'); to inspect it. If the error only happens for some rows, run SELECT your_column FROM your_table WHERE your_column !~ '^\d{4}-\d{2}-\d{2}'; to find the offending values. If the error appears only in a function or trigger, add RAISE NOTICE statements to print the value before the JSON call. If you recently changed the server's TimeZone or DateStyle, compare behaviour before and after; a value that worked under one setting can fail under another. Finally, confirm the PostgreSQL version supports the function you are using: jsonb_set and jsonb_build_object are available from version 9.5 onward, and older versions will give a different error, not 22031.

Frequently Asked Questions

What does PostgreSQL error 22031 mean exactly?

It is the SQLSTATE for "invalid argument for SQL JSON datetime function". It means a value passed to a JSON-related datetime operation could not be converted to a valid date or timestamp.

Is 22031 caused by invalid JSON?

No. The JSON document itself is usually well-formed. The failure is in the datetime value being placed into or extracted from the JSON.

Why does the same query work in one environment but fail in another?

Different DateStyle or TimeZone settings, or different driver versions that serialise dates differently. Compare SHOW DateStyle; and SHOW TimeZone; on both servers.

Can I fix 22031 by changing the column type?

Only if the column currently stores dates as text. Changing it to timestamp or timestamptz removes the ambiguity, but you must clean existing bad values first or the ALTER TABLE will fail.

Does 22031 affect to_json and jsonb_set equally?

Yes. Any function that converts between JSON and datetime types can raise it, including to_json, jsonb_set, jsonb_build_object and direct casts like ::json on a timestamp expression.

Should I store dates as strings inside JSON?

Only if the consumer expects strings. Storing them as ISO 8601 strings is safe and portable, but you lose PostgreSQL's date arithmetic and validation. If you store them as strings, validate on insert.