My first question ever at StackOverflow.
Delphi Embarcadero 10.3 environment. I want access to UTC time. No matter if DST is active or not on my local computer in my time zone, I do not get the correct UTC DateTime. It reports UTC correctly when Daylight Savings Time is active, but as soon as I test after 11/6/22 02:00 AM the resulting UTC output time is 1 hour too early.
A simple function should according to documentation give me UTC as an output and automatically adjust for local DST offset and Timezone. Here is the function:
function UTCNow: TDateTime;
var
UTCnowDateTime: TDateTime;
begin
UTCnowDateTime := TTimezone.Local.ToUniversalTime(Now, True);
Result := UTCnowDateTime;
end;
I tested this by setting local time to 11/6/2022 at 1:59:00 AM.
I call the UTCNow function above and get 11/6/2022 and the UTC time 5:59:06 AM. Then I wait for the time to reach 02:00 AM, where my local computer adjusts for the end of DST and sets the local time to 01:00.
I call the UTCNow function again and get 11/6/2022 and the UTC time 5:00:14 AM. One hour off ! It should be 06:00:14 AM.
(Note: I ran a VB.net test using DateTime.UtcNow and it works correctly across the DST change, but this doesn't help me...)
Any hints ?
CodePudding user response:
For Windows you can call GetSystemTime which gets the time in UTC. Just need to convert it from a Windows SystemTime to a TDateTime.
function UTCNow: TDateTime;
var
ASystemTime: TSystemTime;
UTCnowDateTime: TDateTime;
begin
GetSystemTime(ASystemTime);
UTCnowDateTime := SystemTimeToDateTime(ASystemTime);
Result := UTCnowDateTime;
end;