Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert an ISO 8601 string to a Delphi TDate?

Tags:

iso8601

delphi

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.

like image 630
Roddy Avatar asked Jul 11 '11 14:07

Roddy


People also ask

How do I convert ISO 8601 to date?

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.

How do I convert ISO date to mm dd yyyy?

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);

How do I convert ISO date to long date?

Use the Date() constructor to convert an ISO string to a date object, e.g. new Date('2023-07-21T09:35:31.820Z') .

Is ISO 8601 always UTC?

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 .


2 Answers

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;
like image 103
Jeroen Wiert Pluimers Avatar answered Oct 21 '22 23:10

Jeroen Wiert Pluimers


From XE8 onwards, use ISO8601ToDate (and DateToISO8601) from dateutils.pas.

http://docwiki.embarcadero.com/Libraries/XE8/en/System.DateUtils.ISO8601ToDate

like image 44
Roddy Avatar answered Oct 22 '22 00:10

Roddy