gettimeofday()
<?php //Syntax 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 value0
means the timezone is not on DST.
The following code was executed from my localhost on August 07, 2022, at 08:58:42 CET:
<?php # 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:
<?php 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.
<?php $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.
<?php $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
<?php $tz = date_default_timezone_get(); $time = gettimeofday(); if ($time['dsttime'] === 0) echo "The timezone '$tz' is not on DST.<br>"; else echo "The timezone '$tz' is on DST.<br>"; # Prints: The timezone 'Europe/Berlin' is on DST.
Example: Get UTC offset (hour)
<?php $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:
- PHP DateTime Class
- PHP DateTimeZone Class – times in different countries
- PHP DateInterval Class – adds or subtracts dates/times
- PHP DatePeriod Class – generates date or time ranges
- PHP Validating Age and Date of Birth
- Sunset, Sunrise, Transit, and Twilight
- Localizing Dates
- Localizing Dates with IntlDateFormatter Class