Search code examples
jsondelphi-10.4-sydney

How to handle TDatetime in a TJSONObject


I have a TJSONObject from previous processes and need to add a time-based field at a later stage. How would you recommend to do it? Should I add is a number (Double) or convert to string and later back again?


Solution

  • JSON has no concept of date/time values, so you will have to choose for yourself whether you want to add them as strings or numbers.

    If you use numbers, I would suggest separating the individual components, eg:

    "date": {
      "month": ###,
      "day": ###,
      "year": ###
    },
    "time": {
      "hour": ###,
      "minute": ###,
      "second": ###,
      "msec": ###
    }
    

    If you use strings, I would suggest using a format that is easy to parse back out, like ISO-8601, eg:

    "date": "YYYY-MM-DD",
    "time": "HH:MM:SS.ZZZ"
    

    or:

    "datetime": "YYYY-MM-DDTHH:MM:SS.ZZZ",