[fpc-pascal] How to get UTC time

Pete Cervasio cervasio at airmail.net
Tue Feb 13 17:51:26 CET 2007

On Tuesday 13 February 2007 03:37, Michel Meunier wrote:

> I work on a program wich need the UTC time, and this program will run
> with Windows and Linux.
> So how is it possible to calculate the UTC time under these two OS.

Hello, Michel.

I do not program under Windows, so I cannot answer that part of the question, 
but getting the UTC time under Linux is quite easy.  I have written a utc_now 
function which I use under both Kylix and Free Pascal.  If you can find the 
answer for Windows, then it should be easy enough to combine the two into one 
function with an {$ifdef }.

There may be (and there probably are) better ways of doing it, but this works 
for me.  It needs both the SysUtils and Libc units, which I'm already using 
for other declarations anyway.

// Routine: utc_now
// Purpose: Returns the current UTC time as a TDateTime value.
function utc_now : TDateTime;
  timeval: TTimeVal;
  timezone: PTimeZone;
  a: Double;
  TimeZone := nil;
  GetTimeOfDay (TimeVal, TimeZone);
  // Convert to milliseconds
  a := (TimeVal.tv_sec * 1000.0) + (TimeVal.tv_usec / 1000.0);
  Result := (a / MSecsPerDay) + UnixDateDelta;

I hope this helps,
Pete C.

More information about the fpc-pascal mailing list