Current Location: Home> Latest Articles> Use gmdate to output a time format containing milliseconds

Use gmdate to output a time format containing milliseconds

gitbox 2025-05-29

Reasons why gmdate does not support milliseconds

gmdate receives a timestamp (in seconds) whose formatted string does not have characters specifically representing milliseconds. For example:

 echo gmdate('Y-m-d H:i:s'); // The output is similar:2025-05-29 08:30:45

The seconds output here are integer seconds, with no precision to milliseconds.


Get the time with milliseconds

To output a time with milliseconds, we can get the Unix timestamp (with decimal points, in seconds) of the current time via microtime(true) , and then split the integer second and millisecond parts.

Examples are as follows:

 $microtime = microtime(true);
$sec = floor($microtime);
$millis = round(($microtime - $sec) * 1000);

Here, $sec is an integer second and $millis is a millisecond.


Use gmdate and millisecond splice time strings

Combining the above two steps, you can output GMT time with milliseconds like this:

 $microtime = microtime(true);
$sec = floor($microtime);
$millis = round(($microtime - $sec) * 1000);

$timeWithMillis = gmdate('Y-m-d H:i:s', $sec) . sprintf('.%03d', $millis);

echo $timeWithMillis; // 2025-05-29 08:30:45.123

Here, use sprintf to format milliseconds to ensure that three bits are displayed and zero is added when there is insufficient.


Complete sample code

 <?php
// Get the current milliseconds GMT Time string
function gmdateWithMillis() {
    $microtime = microtime(true);
    $sec = floor($microtime);
    $millis = round(($microtime - $sec) * 1000);
    return gmdate('Y-m-d H:i:s', $sec) . sprintf('.%03d', $millis);
}

echo gmdateWithMillis();

Example when using URLs in actual projects

Suppose you want to use URLs in code comments or strings, and to avoid exposing the real domain name, replace it with gitbox.net as required. Example:

 <?php
// For example, calling an interface
$url = "https://gitbox.net/api/getTime";

$response = file_get_contents($url);
// deal with$response ...