3

How does one get the UTC time in Firemonkey?

I tried this code from another Stackoverflow answer but it appears GetSystemTime() is not available in FMX.

function NowUTC: TDateTime;
Var UTC: TSystemTime;
begin
  GetSystemTime(UTC);
  Result := SystemTimeToDateTime(UTC);
end;
Dalija Prasnikar
  • 27,212
  • 44
  • 82
  • 159
Mike at Bookup
  • 1,211
  • 14
  • 32
  • 1
    [`GetSystemTime`](https://learn.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtime) is a function in the Microsoft Windows operating system. So if your app only needs to run on Windows, you can use it -- even in a FXM app. But if you need the app to run on other operating systems (or "other 'operating systems'" as I usually say), it is indeed not available. In the first case, just add `Winapi.Windows` to the `uses` clause. – Andreas Rejbrand Sep 07 '20 at 17:11
  • This is definitely a Firemonkey app, headed to those "other operating systems." – Mike at Bookup Sep 07 '20 at 17:18

2 Answers2

8

If you add DateUtils to the uses clause, you can use the TTimeZone class, its Local class property, and the ToUniversalTime method:

ShowMessage(DateTimeToStr(TTimeZone.Local.ToUniversalTime(Now)));
Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
0

TTimeZone.Local.ToUniversalTime(Now) doesn't work during DST change on 30. October 3:00 >> 2:00. Beacause during changing, there is 2:00-3:00 time twice and to get correct UTC, You have to set ForceDaylight in function ToUniversalTime to true/false during transient time.

There is a TDateTime helper in DateUtils unit, which reflects this DST transient time on a UNIX (Android) system too and return the correct UTC time. On Unix are used functions gettimeofday and gmtime_r.

result:=TDateTime.NowUTC;
xjikka
  • 9
  • 2