Tech Tip: Date Data Types in Objects
PRODUCT: 4D | VERSION: 16R6 | PLATFORM: Mac & Win
Published On: January 25, 2018
In 4D v16 R6 the JSON Parse command has been improved to be able to parse Date values into Date type data. To enable this feature the Compatibility Database Setting "Use date type instead of ISO date format in objects" must be enabled:
This allows JSON Stringify to translate dates into YYYY-MM-DD format and allows JSON Parse to parse date values into one of three formats set with the SET DATABASE PARAMETER command and the Dates inside objects (85) selector:
- String type without time zone (0)
- String type with time zone (1) (default)
- Date type (2)
With "Use date type instead of ISO date format in objects" disabled and in older versions of 4D the following code:
$original_ob:=New object("date";Current date) $stringOb_t:=JSON Stringify($original_ob) TRACE |
Generates the following:
Enabling the setting and running the same code results in:
The JSON Parse command is independent of the setting and instead is based on how the JSON string has the date formatted.
If the Date is formatted in YYYY-MM-DD then it will generate an object based on the database settings as shown in the following code:
$stringOb_t:="{\"date\":\"2018-01-24\"}" SET DATABASE PARAMETER(Dates inside objects;String type without time zone) $res1_ob:=JSON Parse($stringOb_t) SET DATABASE PARAMETER(Dates inside objects;String type with time zone) $res2_ob:=JSON Parse($stringOb_t) SET DATABASE PARAMETER(Dates inside objects;Date type) $res3_ob:=JSON Parse($stringOb_t) TRACE |
This will result in the following with the third format parsed as a Date data type:
If the Date is formatted in ISO date format then all results will be a string:
$stringOb_t:="{\"date\":\"2018-01-24T08:00:00.000Z\"}" SET DATABASE PARAMETER(Dates inside objects;String type without time zone) $res1_ob:=JSON Parse($stringOb_t) SET DATABASE PARAMETER(Dates inside objects;String type with time zone) $res2_ob:=JSON Parse($stringOb_t) SET DATABASE PARAMETER(Dates inside objects;Date type) $res3_ob:=JSON Parse($stringOb_t) TRACE |