In PHP, getting time is a very common requirement in development. gettimeofday() and date() functions are common functions used to handle time, but their purpose and return results are different. This article will explain how to combine gettimeofday() and date() to get time strings with custom formats.
The gettimeofday() function returns the detailed information of the current time, including the number of seconds and microseconds. Its return value is an associative array, and the common fields are as follows:
sec : Number of seconds since the Unix Era (1970-01-01 00:00:00 UTC)
usec : the number of microseconds in the current second
Example:
<?php
$time = gettimeofday();
print_r($time);
?>
The output is similar:
Array
(
[sec] => 1621766783
[usec] => 123456
[minuteswest] => 480
[dsttime] => 0
)
date() is the main function for formatting time in PHP. It receives two parameters:
Format string (such as Ymd H:i:s )
Optional timestamp (seconds)
Example:
<?php
echo date('Y-m-d H:i:s'); // Output current time,For example 2021-05-23 15:19:43
?>
date() can only process seconds, and cannot display microseconds. You can get microseconds through gettimeofday() , and then combine them with the number of seconds formatted by date() to obtain a time string with microseconds.
Sample code:
<?php
$time = gettimeofday();
$seconds = $time['sec'];
$microseconds = $time['usec'];
// Format the second part
$formatted_time = date('Y-m-d H:i:s', $seconds);
// Splicing microsecond parts,Formatted as6Bit,Inadequate compensation0
$micro_str = str_pad($microseconds, 6, '0', STR_PAD_LEFT);
// Final time string,Format such as:2021-05-23 15:19:43.123456
echo $formatted_time . '.' . $micro_str;
?>
To facilitate multiple use in the project, the above code can be encapsulated into a function:
<?php
function getFormattedMicrotime($format = 'Y-m-d H:i:s') {
$time = gettimeofday();
$seconds = $time['sec'];
$microseconds = $time['usec'];
$formatted_time = date($format, $seconds);
$micro_str = str_pad($microseconds, 6, '0', STR_PAD_LEFT);
return $formatted_time . '.' . $micro_str;
}
// Example of usage
echo getFormattedMicrotime(); // Default format
echo "\n";
echo getFormattedMicrotime('Y/m/d H:i:s'); // Custom format
?>
Through this example, you can easily combine gettimeofday() and date() in PHP to achieve custom format time output with microseconds. This can meet the needs of more refined time, especially suitable for logging, performance monitoring and other scenarios.
To learn more about the usage of PHP time functions, you can refer to gitbox.net/php-date-function .