gpt4 book ai didi

datetime - 将这些时间从 UTC 转换为本地时间我做错了什么?

转载 作者:行者123 更新时间:2023-12-03 19:36:37 24 4
gpt4 key购买 nike

使用 GitHub API,时间戳以 UTC 格式返回。我正在使用以下内容将这些转换为 Delphi TDateTime ...

  with TXSDateTime.Create do
try
XSToNative('2019-07-27T19:33:02Z');
Result:= AsDateTime;
finally
Free;
end;

我不记得我在哪里找到该功能。

2019-07-27T19:33:02Z直接来自特定存储库的“pushed_at”字段(最后推送)上的 GitHub API。使用上面的函数将其转换后,我得到(格式化为字符串):
2019-07-27 11:33:02
现在我采用这个值并尝试将其转换为本地时间。我的本地时间是美国东部时间,我知道我昨天下午 3:33 上次推送的特定存储库。我直接在 GitHub 的网站上确认了这一点。

我使用了 the top two answers on this question 中的两种方法.特别是函数 LocalDateTimeFromUTCDateTimeUnivDateTime2LocalDateTime然而,结果都是倒退的。两种方法都不是增加 4 小时,而是减去 4 小时。

所以我从两者得到的结果是
2019-07-27 07:33:02
我知道我没有在早上 7:33 做那个推送。我什至还没醒。

其实如果我用错了函数 DateTime2UnivDateTime()然后我实际上得到了正确的结果。

我在这里做错了什么,如何获得本地时间的正确结果?

我几乎不了解时区背后的科学。

编辑

看起来第一个函数导致时移加倍,所以我没有意识到它已经在尝试转换为本地时间。但不是减去 4 小时,而是减去了 8 小时。所以我被甩了,我想我仍然需要将它转换为本地时间。但为什么它会转移两次?

最佳答案

1)将ISO时间转换为Delphi TDateTime:

function ISOToDateTime(const AISODateTime: string): TDateTime;
var
I: Integer;
VDate, VTime: TDateTime;
VFormatSettings: TFormatSettings;
begin
// ISO format: 2009-07-06T01:53:23Z

VFormatSettings.DateSeparator := '-';
VFormatSettings.ShortDateFormat := 'yyyy-mm-dd';
VFormatSettings.TimeSeparator := ':';
VFormatSettings.ShortTimeFormat := 'hh:nn:ss';

I := Pos('T', AISODateTime);
VDate := StrToDate(Copy(AISODateTime, 1, I - 1), VFormatSettings);
VTime := StrToTime(Copy(AISODateTime, I + 1, 8), VFormatSettings);

Result := Trunc(VDate) + Frac(VTime);
end;

2)将UTC时间转换为本地时间:
function UniversalToLocalTime(const AUtcTime: TDateTime): TDateTime;

function _GetSystemTzOffset: Extended;
var
VTmpDate: TDateTime;
ST1, ST2: TSystemTime;
TZ: TTimeZoneInformation;
begin
GetTimeZoneInformation(TZ);
DateTimeToSystemTime(AUtcTime, ST1);
SystemTimeToTzSpecificLocalTime(@TZ, ST1, ST2);
VTmpDate := SystemTimeToDateTime(ST2);
Result := MinutesBetween(VTmpDate, AUtcTime) / 60;
if VTmpDate < AUtcTime then begin
Result := -Result;
end;
end;

var
VOffset: Extended;
begin
VOffset := _GetSystemTzOffset;
if VOffset = 0 then begin
Result := AUtcTime;
end else begin
Result := IncHour(AUtcTime, Trunc(VOffset));
Result := IncMinute(Result, Round(Frac(VOffset) * 60));
end;
end;

关于datetime - 将这些时间从 UTC 转换为本地时间我做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57243647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com