Author: Tomas Rutkauskas
Does anybody know of any API or component that will convert a local datetime into
GMT/UTC, using the Windows settings?
Answer:
Solve 1:
1 function NowUTC: TDateTime;
2 var3 system_datetime: TSystemTime;
4 begin5 GetSystemTime(system_datetime);
6 Result := SystemTimeToDateTime(system_datetime);
7 end;
Solve 2:
8 { ... }9 const10 MinsPerDay = 24 * 60;
11 12 function GetGMTBias: Integer;
13 var14 info: TTimeZoneInformation;
15 Mode: DWord;
16 begin17 Mode := GetTimeZoneInformation(info);
18 Result := info.Bias;
19 case Mode of20 TIME_ZONE_ID_INVALID:
21 RaiseLastOSError;
22 TIME_ZONE_ID_STANDARD:
23 Result := Result + info.StandardBias;
24 TIME_ZONE_ID_DAYLIGHT:
25 Result := Result + info.DaylightBias;
26 end;
27 end;
28 29 function GMTNow: TDateTime;
30 begin31 Result := LocaleToGMT(Now);
32 end;
33 34 function LocaleToGMT(const Value: TDateTime): TDateTime;
35 begin36 Result := Value + (GetGMTBias / MinsPerDay);
37 end;
38 39 function GMTToLocale(const Value: TDateTime): TDateTime;
40 begin41 Result := Value - (GetGMTBias / MinsPerDay);
42 end;
Solve 3:
43 44 function MakeUTCTime(DateTime: TDateTime): TDateTime;
45 var46 TZI: TTimeZoneInformation;
47 begin48 case GetTimeZoneInformation(TZI) of49 TIME_ZONE_ID_STANDARD:
50 begin51 Result := DateTime + (TZI.Bias / 60 / 24);
52 end;
53 TIME_ZONE_ID_DAYLIGHT:
54 begin55 Result := DateTime + (TZI.Bias / 60 / 24) + TZI.DaylightBias;
56 end57 else58 raise59 Exception.Create('Error converting to UTC Time. Time zone could not be
60 determined.'
61 end;
62 end;
It's probably worth pointing out that this function will only work if the source of the TDateTime being converted was the system clock on the local machine (rather than, say, a field in a database or disk file) and if the timezone hasn't changed (e.g. between daylight saving and standard time) since the date was recorded.