hello, i am new to CT and was searching for some practice.
i did played abit with code and for windows this solution came out, maybe usfull or not, you decide, for me just fun to do
program Project1;
uses Windows, SysUtils, DateUtils;
// include winapi methods
function TzSpecificLocalTimeToSystemTime(lpTimeZoneInformation: PTimeZoneInformation; var lpLocalTime, lpUniversalTime: TSystemTime): BOOL; stdcall; external kernel32 name 'TzSpecificLocalTimeToSystemTime';
function SystemTimeToTzSpecificLocalTime(lpTimeZoneInformation: PTimeZoneInformation; var lpUniversalTime, lpLocalTime: TSystemTime): BOOL; stdcall; external kernel32 name 'SystemTimeToTzSpecificLocalTime';
// convert local time to UTC
function DateTimeToUTC(const Local: TDateTime): TDateTime;
var
TZI: TTimeZoneInformation;
LocalTime,
UniversalTime: TSystemTime;
begin
GetTimeZoneInformation(TZI);
DateTimeToSystemTime(Local, LocalTime);
TzSpecificLocalTimeToSystemTime(@TZI, LocalTime, UniversalTime);
Result := SystemTimeToDateTime(UniversalTime);
end;
// convert UTC to local time
function UTCToLocalDateTime(const UTC: TDateTime): TDateTime;
var
TZI: TTimeZoneInformation;
LocalTime,
UniversalTime: TSystemTime;
begin
GetTimeZoneInformation(TZI);
DateTimeToSystemTime(UTC, UniversalTime);
SystemTimeToTzSpecificLocalTime(@TZI, UniversalTime, LocalTime);
Result := SystemTimeToDateTime(LocalTime);
end;
// example usage
var
Local,
UTC: TDateTime;
begin
Local := Now;
UTC := DateTimeToUTC(Local);
WriteLn('Local: ' + DateTimeToStr(Local));
WriteLn('UTC: ' + DateTimeToStr(UTC));
WriteLn('Offset: ' + IntToStr(SecondsBetween(Local, UTC) div 60 div 60));
ReadLn;
end.