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

前端之家收集整理的这篇文章主要介绍了delphi – 以字符串格式存储日期值的最佳方式是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我必须以字符串格式存储日期值(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”.

为了获得更好的分辨率,您可以通过在逗号或点号之后添加分数来添加次秒钟定时.以“14:30:10,5”,“143010,“14:30:10.5”或“143010.5”表示“14小时30分10秒500毫秒”.您可以添加几个小数位以提高分辨率.

如果您需要快速的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 /双内存结构的Int64二进制版本将比任何其他浮点相关转换快.

原文链接:https://www.f2er.com/delphi/102649.html

猜你在找的Delphi相关文章