如何在 Delphi 中将本地时间转换为 UTC 时间?以及如何将其从 UTC 转换回本地时间? [英] How to convert Local time to UTC time in Delphi? and how to convert it back from UTC to local time?

查看:81
本文介绍了如何在 Delphi 中将本地时间转换为 UTC 时间?以及如何将其从 UTC 转换回本地时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Delphi 并且我试图在我的数据库中使用 UTC 日期时间存储记录,然后当客户端在他的本地日期时间读取它时将其恢复?知道如何进行这种前向转换吗?

I'm using Delphi and I'm trying to store records using UTC datetime in my database and then restore it back when a client reads it in his local datetime ? any idea how to do this forth back conversion ?

推荐答案

这是我用来从 UTC 转换为本地的函数.

This is the function that I use to convert from UTC to local.

function LocalDateTimeFromUTCDateTime(const UTCDateTime: TDateTime): TDateTime;
var
  LocalSystemTime: TSystemTime;
  UTCSystemTime: TSystemTime;
  LocalFileTime: TFileTime;
  UTCFileTime: TFileTime;
begin
  DateTimeToSystemTime(UTCDateTime, UTCSystemTime);
  SystemTimeToFileTime(UTCSystemTime, UTCFileTime);
  if FileTimeToLocalFileTime(UTCFileTime, LocalFileTime) 
  and FileTimeToSystemTime(LocalFileTime, LocalSystemTime) then begin
    Result := SystemTimeToDateTime(LocalSystemTime);
  end else begin
    Result := UTCDateTime;  // Default to UTC if any conversion function fails.
  end;
end;

如您所见,该函数按如下方式转换 UTC 日期时间:

As you can see the function transforms the UTC date time as follows:

  • 日期时间 -> 系统时间
  • 系统时间 -> 文件时间
  • 文件时间 -> 本地文件时间(这是从 UTC 到本地的转换)
  • 本地文件时间 -> 系统时间
  • 系统时间 -> 日期时间

如何扭转这一点应该是显而易见的.

It should be obvious how to reverse this.

请注意,此转换将夏令时视为现在,而不是转换时.DateUtils.TTimeZone 类型,在XE,正试图做到这一点.代码变为:

Note that this conversion treats daylight saving as it is now rather than as it is/was at the time being converted. The DateUtils.TTimeZone type, introduced in XE, attempts to do just that. The code becomes:

LocalDateTime := TTimeZone.Local.ToLocalTime(UniversalDateTime);

在另一个方向使用 ToUniversalTime.

这个类似乎是(松散地)模仿 .net TimeZone 类.

This class appears to be (loosely) modelled on the .net TimeZone class.

警告.不要指望 尝试 将夏令时转换为 100% 准确.实现这一目标是不可能的.至少没有时光机.这只是考虑到未来的时间.即使过去的时代也很复杂.Raymond Chen 在这里讨论了这个问题:为什么夏令时不直观.

A word of warning. Do not expect the attempt to account for daylight savings at the time being converted to be 100% accurate. It is simply impossible to achieve that. At least without a time machine. And that's just considering times in the future. Even times in the past are complex. Raymond Chen discusses the issue here: Why Daylight Savings Time is nonintuitive.

这篇关于如何在 Delphi 中将本地时间转换为 UTC 时间?以及如何将其从 UTC 转换回本地时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆