I can convert a Delphi TDate to ISO 8601 format easily using this:
DateTimeToString(result, 'yyyy-mm-dd', myDate);
What's the idiomatic way to do the inverse conversion? StringToDateTime()
doesn't seem to exist.
Obviously I can do it the "hard" way by manually parsing the string and encoding the result, but that seems a poor choice.
toISOString() method is used to convert the given date object's contents into a string in ISO format (ISO 8601) i.e, in the form of (YYYY-MM-DDTHH:mm:ss. sssZ or ±YYYYYY-MM-DDTHH:mm:ss. sssZ). The date object is created using date() constructor.
To convert an ISO date to the date format yyyy-mm-dd with JavaScript, we can call the string substring method. const date = new Date("2022-03-10T02:00:00Z"); const isoDate = date. toISOString(). substring(0, 10);
Use the Date() constructor to convert an ISO string to a date object, e.g. new Date('2023-07-21T09:35:31.820Z') .
Date.prototype.toISOString() The toISOString() method returns a string in simplified extended ISO format (ISO 8601), which is always 24 or 27 characters long ( YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ , respectively). The timezone is always zero UTC offset, as denoted by the suffix Z .
why re-invent the wheel?
XML uses ISO 8601 for date and date-time storage.
Delphi has had built-in support for that since Delphi 6 in the XSBuiltIns unit.
This answer explains how for DateTime, this is for Date only using the TXSDate class:
with TXSDate.Create() do
try
AsDate := Date; // convert from TDateTime
DateString := NativeToXS; // convert to WideString
finally
Free;
end;
with TXSDate.Create() do
try
XSToNative(DateString); // convert from WideString
Date := AsDate; // convert to TDateTime
finally
Free;
end;
From XE8 onwards, use ISO8601ToDate
(and DateToISO8601
) from dateutils.pas
.
http://docwiki.embarcadero.com/Libraries/XE8/en/System.DateUtils.ISO8601ToDate
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With