问题描述
我正在使用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转换回当地时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!