### Bookstore

 Computer Math and Games in Pascal (preview) Lazarus Handbook

### Author Topic: Use UNIX function (localtime)  (Read 843 times)

#### DevilDevil

• New Member
• Posts: 32
##### Re: Use UNIX function (localtime)
« Reply #15 on: April 07, 2020, 09:48:35 am »
I found a way to get UTC time and calculate local! Thanks to all

Code: Pascal  [Select][+][-]
1. {\$if Defined(FPC) and Defined(UNIX)}
2. const
3.   libc = 'libc.so';
4.
5. type
6.   tm = packed record
7.     tm_sec: Integer;            // Seconds. [0-60] (1 leap second)
8.     tm_min: Integer;            // Minutes. [0-59]
9.     tm_hour: Integer;           // Hours.[0-23]
10.     tm_mday: Integer;           // Day.[1-31]
11.     tm_mon: Integer;            // Month.[0-11]
12.     tm_year: Integer;           // Year since 1900
13.     tm_wday: Integer;           // Day of week [0-6] (Sunday = 0)
14.     tm_yday: Integer;           // Days of year [0-365]
15.     tm_isdst: Integer;          // Daylight Savings flag [-1/0/1]
16.     tm_gmtoff: Integer;         // Seconds east of UTC
17.     tm_zone: PAnsiChar;         // Timezone abbreviation
18.   end;
19.   Ptm = ^tm;
20.
21. function localtime(var Timer: time_t): Ptm; cdecl; external libc name 'localtime';
22. {\$ifend}
23.
24. class function TOSTime.UpdateLocalDelta: Int64;
25. {\$ifdef MSWINDOWS}
26. var
27.   LUTCTime: TFileTime;
28.   LLocalTime: TFileTime;
29. begin
30.   GetSystemTimeAsFileTime(LUTCTime);
31.   FileTimeToLocalFileTime(LUTCTime, LLocalTime);
32.   Result := Int64(LLocalTime) - Int64(LUTCTime);
33.   TIMESTAMP_LOCAL_DELTA := Result;
34. end;
35. {\$else .POSIX}
36. var
37.   Ltm: Ptm;
38.   LUtcTime: timespec;
39.   LLocalTime: time_t;
40. begin
41.   clock_gettime(CLOCK_REALTIME_COARSE, @LUtcTime);
42.   Ltm := localtime(LUtcTime.tv_sec);
43.   LLocalTime := Ltm.tm_sec + Ltm.tm_min * 60 + Ltm.tm_hour * 3600 + Ltm.tm_yday * 86400 +
44.     (Ltm.tm_year - 70) * 31536000 + ((Ltm.tm_year - 69) div 4) * 86400 -
45.     ((Ltm.tm_year - 1) div 100) * 86400 + ((Ltm.tm_year + 299) div 400) * 86400;
46.
47.   Result := (LLocalTime - LUtcTime.tv_sec) * TIMESTAMP_SECOND;
48.   TIMESTAMP_LOCAL_DELTA := Result;
49.   TIMESTAMP_REALTIMESTAMP_LOCAL_DELTA := TIMESTAMP_REALTIME_DELTA + Result;
50. end;
51. {\$endif}