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.
You can find Iso-8601 conversion routines in our SynCommons unit.
It has been deeply optimized for speed, so it's much faster than the DateTimeToString() functions and such, but of course, code is more difficult to follow. ;)
This is able to handle a very fast conversion from an UTF-8 encoded buffer into a
TDateTime
. For all constants dependencies, check the unit source code.For more flexibility, you could consider Marco van de Voort's scandate routine which handles your string in any format:
See final version (7kB .zip) as added to FPC.
From XE8 onwards, use
ISO8601ToDate
(andDateToISO8601
) fromdateutils.pas
.http://docwiki.embarcadero.com/Libraries/XE8/en/System.DateUtils.ISO8601ToDate
Starting with XE6 you can use function
System.DateUtils.ISO8601ToDate
: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:
I think this should work... the documentation says the overloaded version of these methods is for use in threads, but it can be handy for specifying the format settings you wish to use at the time.
You can of course write variants of this with StrToDateDef and TryStrToDate with equivalent functionality