[Lazarus] UnixToDateTime and time zone
Dibo
dibo20 at wp.pl
Fri Sep 17 15:37:35 CEST 2010
Dnia 2010-09-17, piÄ… o godzinie 01:55 +0300, Alberto Narduzzi pisze:
> Dibo,
>
> > Is there a function in FPC that returns me my local UTC offset?
>
> never tested them, thou' have a look at DateTimeToUnix and
> UnixToDateTime, in unit DateUtils
>
> HTH
UnixToDateTime and DateTimeToUnix don't uses any GMT/UTC calculation.
They just convert date time just as it is. I search internet for time
zone information in delphi and I found this article:
http://delphicikk.atw.hu/listaz.php?id=2667&oldal=52
I change his code to free pascal cross platform and this is working
function (tested on windows and linux):
uses dateutils, {$IFDEF MSWINDOWS} windows {$ENDIF} {$IFDEF UNIX}
unixutil {$ENDIF}
function UniversalTimeToLocal(UT: TDateTime): TDateTime;
var
LT: TDateTime;
TZOffset: Integer;
{$IFDEF MSWINDOWS}
BiasType: Byte;
TZInfo: TTimeZoneInformation;
{$ENDIF}
begin
LT := UT;
{$IFDEF MSWINDOWS}
BiasType := GetTimeZoneInformation(TZInfo);
if (BiasType=0) then begin
Result := UT;
Exit;
end;
// Determine offset in effect for DateTime UT.
if (BiasType=2) then
TZOffset := TZInfo.Bias + TZInfo.DaylightBias
else
TZOffset := TZInfo.Bias + TZInfo.StandardBias;
{$ENDIF}
{$IFDEF UNIX}
TZOffset := -Tzseconds div 60;
{$ENDIF}
// 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;
Demo:
procedure TForm1.Button1Click(Sender: TObject);
var
d: TDateTime;
begin
// This is unix time 2010-07-26 17:50:17
d := UnixToDateTime(1280166617);
d := UniversalTimeToLocal(d);
// After convert we get 2010-07-26 19:50:17 (Poland GMT + 2h)
Edit1.Text := DateTimeToStr(d);
end;
I am surprised that Free Pascal does not have so basic function. Should
I post it on mantis as proposition?
> Cheers, A.
>
> --
> _______________________________________________
> Lazarus mailing list
> Lazarus at lists.lazarus.freepascal.org
> http://lists.lazarus.freepascal.org/mailman/listinfo/lazarus
>
More information about the Lazarus
mailing list