如何将 ISO 8601 字符串转换为 Delphi TDate?
我可以使用以下方法轻松将 Delphi TDate 转换为 ISO 8601 格式:
DateTimeToString(result, 'yyyy-mm-dd', myDate);
What's the idioma way to do the inverse conversion? StringToDateTime()
似乎不存在。
显然,我可以通过手动解析字符串并对结果进行编码来以“硬”方式完成此操作,但这似乎是一个糟糕的选择。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
为什么要重新发明轮子?
XML 使用 ISO 8601 进行日期和日期时间存储。
自 Delphi 6 以来,Delphi 已在 XSBuiltIns 单元。
这个答案解释了如何 对于 DateTime,这仅适用于使用 TXSDate 类:
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:
从 XE8 开始,使用
dateutils.pas
中的ISO8601ToDate
(和DateToISO8601
)。http://docwiki.embarcadero.com/Libraries/XE8/en/System .DateUtils.ISO8601ToDate
From XE8 onwards, use
ISO8601ToDate
(andDateToISO8601
) fromdateutils.pas
.http://docwiki.embarcadero.com/Libraries/XE8/en/System.DateUtils.ISO8601ToDate
我认为这应该有效...文档说这些方法的重载版本用于线程中,但它可以方便地指定您当时希望使用的格式设置。
您当然可以使用 StrToDateDef 和 TryStrToDate 编写具有等效功能的变体
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
您可以在我们的 SynCommons 单元 中找到 Iso-8601 转换例程。
它对速度进行了深度优化,因此它比 DateTimeToString() 函数等快得多,但当然,代码更难以理解。 ;)
这能够处理从 UTF-8 编码缓冲区到
TDateTime
的快速转换。对于所有常量依赖项,请检查单元源代码。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.为了获得更大的灵活性,您可以考虑 Marco van de Voort 的 scandate 例程 处理任何字符串格式:
请参阅添加到 FPC 的最终版本 (7kB .zip)。
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.
德尔福XE3
Delphi XE3
从 XE6 开始,您可以使用函数
System.DateUtils.ISO8601ToDate
:Starting with XE6 you can use function
System.DateUtils.ISO8601ToDate
: