delphi - 以字符串格式存储日期值的最佳方法是什么?

标签 delphi date delphi-xe date-format

我必须以字符串格式存储日期值 (TDateTime)。做这个的最好方式是什么?我考虑了以下方法:

FloatToStr:失去精度,取决于区域设置

带有格式设置的“FloatToStr”:失去精度

DateTimeToStr:取决于区域设置

DateTimeToStr 格式设置:?

还有其他选择吗?他们的比较如何

  • 内存大小
  • 独立于区域设置
  • 精确

最佳答案

使用 ISO-8601 格式,详见http://en.wikipedia.org/wiki/ISO_8601

如果需要节省存储空间,可以使用“紧凑”布局,例如“20090621T054523”。

您可以使用例如FormatDateTime('yyyymmddThhnnss',aDateTime) 来生成它。

关于时区和本地化(来自维基百科):

There are no time zone designators in ISO 8601. Time is only represented as local time or in relation to UTC.

If no UTC relation information is given with a time representation, the time is assumed to be in local time. While it may be safe to assume local time when communicating in the same time zone, it is ambiguous when used in communicating across different time zones. It is usually preferable to indicate a time zone (zone designator) using the standard’s notation.

因此,您最好将时间转换为 UTC,然后在时间戳末尾附加“Z”。或者根据您本地的时区使用+hh/-hh。 以下时间均指同一时刻:“18:30Z”、“22:30+04”、“1130-0700”和“15:00-03:30”。 p>

为了获得更好的分辨率,您可以通过在逗号或点字符后添加分数来添加亚秒计时:例如要表示“14 小时、30 分钟、10 秒和 500 毫秒”,请将其表示为“14:30:10,5”、“143010,5”、“14:30:10.5”或“143010.5”。您可以添加几位小数以提高分辨率。

如果您需要快速Iso8601转换例程(处理UTF-8内容),请查看SynCommons.pas中的相应部分。它比默认的 SysUtils 函数快得多。

PS:

如果您的目的只是将 TDateTime 作为文本存储在纯 Delphi 应用程序中,您可以使用非标准但速度很快:

function DateTimeToText(const aDateTime: TDateTime): string;
begin
  result := IntToStr(PInt64(@aDateTime)^);
end;

function TextToDateTime(const aText: string): TDateTime;
begin
  PInt64(@result)^ := StrToInt64Def(aText,0);
end;

使用 TDateTime/double 内存结构的 Int64 二进制布局将比任何其他浮点相关转换更快。

关于delphi - 以字符串格式存储日期值的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6055248/

相关文章:

delphi - OLE自动化: How to check if a variant references an automation object

java - 如何解析从周/年到dd/mm/yyyy

delphi - Turbo Power - 用于 Delphi XE 的 SongBeamer 或 SourceForge?

Linq 日期和日期时间比较器

sql - 按星期几按小时计算的平均计数

delphi - 是否可以在 delphi 类上定义虚拟静态成员?

delphi - Delphi 应用程序什么时候对于单个 EXE 来说太大?

delphi - 当我使用完 SQLite DLL 后,如果操作系统认为它仍在使用中,如何删除它?

delphi - 属性不继承?

delphi - 在 Delphi XE2 应用程序中双击 TStaticText 将标题复制到剪贴板