New functions for time zone
Original Reporter info from Mantis: Dibo
-
Reporter name: Krzysztof Dibowski
Original Reporter info from Mantis: Dibo
- Reporter name: Krzysztof Dibowski
Description:
Hi,
I don't know why, but I can't post issue on FPC category (blank page), so please move this topic to right project.
I couldn't find functions responsible for conversion between unix time stamp and TDateTime including time zone. UnixToDateTime and DateTimeToUnix convert dates just as it is without time zone. So I found this delphi article:
http://delphicikk.atw.hu/listaz.php?id=2667&oldal=52
... and change his functions to free pascal cross platform. I think it's one of the fundamental functions so I'm suprised that FPC doesn't have they yet (or I could not find them) Is there any chance of adding them to the source?
uses dateutils, {$IFDEF MSWINDOWS} windows {$ENDIF} {$IFDEF UNIX} unixutil {$ENDIF};
function GetLocalTimeOffset: Integer;
{$IFDEF MSWINDOWS}
var
BiasType: Byte;
TZInfo: TTimeZoneInformation;
const
BS_TYPE_UKNOWN = 0 { Unknown };
BS_TYPE_STANDARD = 1 { Standard Time };
BS_TYPE_DAYLIGHT = 2 { Daylight Time };
{$ENDIF}
begin
Result := 0;
{$IFDEF MSWINDOWS}
BiasType := GetTimeZoneInformation(TZInfo);
if (BiasType=BS_TYPE_UKNOWN) then Exit;
// Determine offset in effect for DateTime UT.
if (BiasType=BS_TYPE_DAYLIGHT) then
Result := TZInfo.Bias + TZInfo.DaylightBias
else if (BiasType=BS_TYPE_STANDARD) then
Result := TZInfo.Bias + TZInfo.StandardBias;
{$ENDIF}
{$IFDEF UNIX}
Result := -Tzseconds div 60;
{$ENDIF}
end;
function UniversalTimeToLocal(UT: TDateTime): TDateTime;
var
LT: TDateTime;
TZOffset: Integer;
begin
LT := UT;
TZOffset := GetLocalTimeOffset;
// Apply offset.
if (TZOffset > 0) then
// Time zones west of Greenwich.
LT := UT - EncodeTime(TZOffset div 60, TZOffset mod 60, 0, 0)
else if (TZOffset = 0) then
// Time Zone = Greenwich.
LT := UT
else if (TZOffset < 0) then
// Time zones east of Greenwich.
LT := UT + EncodeTime(Abs(TZOffset) div 60, Abs(TZOffset) mod 60, 0, 0);
// Return Local Time.
Result := LT;
end;
function LocalTimeToUniversal(LT: TDateTime): TDateTime;
var
UT: TDateTime;
TZOffset: Integer; // Offset in minutes.
begin
// Initialize UT to something,
// so compiler doesn't complain.
UT := LT;
// Determine offset in effect for DateTime LT.
TZOffset := GetLocalTimeOffset;
// Apply offset.
if (TZOffset > 0) then
// Time zones west of Greenwich.
UT := LT + EncodeTime(TZOffset div 60, TZOffset mod 60, 0, 0)
else if (TZOffset = 0) then
// Time Zone = Greenwich.
UT := LT
else if (TZOffset < 0) then
// Time zones east of Greenwich.
UT := LT - EncodeTime(Abs(TZOffset) div 60, Abs(TZOffset) mod 60, 0, 0);
// Return Universal Time.
Result := UT;
end;
Additional information:
Tested on Windows and Linux, country: Poland (GMT +2h)