Get Time of day, UTC offset, and DST

The gettimeofday() function executes the underlying gettimeofday(2) system call, it returns the current time (expressed as seconds and microseconds since the Epoch), time zone, and daylight saving time correction information.


 gettimeofday(bool $as_float = false): array|float

By default, an array is returned. If the parameter $as_float is set, then a float is returned. The array contains the following keys and values:

  • sec – seconds since the Unix Epoch (see Generating a Timestamp)
  • usec – microseconds (adds to the number of seconds), also see microtime() function.
  • minuteswest – minutes west of Greenwich (UTC offset)
  • dsttime – type of daylight saving time correction, the value 0 means the timezone is not on DST.

The following code was executed from my localhost on August 07, 2022, at 08:58:42 CET:

 # returns an array
 $time = gettimeofday();
 print_r( $time );
 /* [sec] => 1659855522
    [usec] => 175872
    [minuteswest] => -120
    [dsttime] => 1  */
 # returns a float value
 echo gettimeofday ( TRUE );
 # Prints: 1659855522.1759

Example: gettimeofday(true) vs. microtime(true)

Both gettimeofday(true) and microtime(true) functions return the same result if the optional parameter is provided:

 echo gettimeofday(true);
 # Prints: 1659930415.9927

 echo microtime(true);
 # Prints: 1659930415.9927

Example: time() function vs. gettimeofday[‘sec’]

The time() function and the sec element of the gettimeofday() function returns the current timestamp, see Generating a Timestamp tutorial.

 $gtod = gettimeofday();
 echo $gtod['sec'].'<br>';
 # Prints: 1659931318
 echo time(); 
 # Prints: 1659931318

You can use the date() and getdate() functions to convert a timestamp to date and time.

 $gtod = gettimeofday();
 $tstmp = $gtod['sec'];
 echo date ('d-M-Y H:i:s', $tstmp);
 # Prints: 08-Aug-2022 06:17:50

Example: Check if the current timezone is on DST

 $tz = date_default_timezone_get();
 $time = gettimeofday();
 if ($time['dsttime'] === 0)
  echo "The timezone '$tz' is not on DST.<br>";
  echo "The timezone '$tz' is on DST.<br>";

 # Prints: The timezone 'Europe/Berlin' is on DST.

Example: Get UTC offset (hour)

 $tz = date_default_timezone_get();
 $time = gettimeofday();
 # Converting minutes to hours
 $offset = $time['minuteswest'] / 60;
 echo "The '$tz' timezone is $offset hour(s) west of UTC.";
 # The 'Europe/Berlin' timezone is -2 hour(s) west of UTC.

The Date and Time Tutorials: