當前位置: 首頁> 最新文章列表> 使用gmdate 輸出含有毫秒的時間格式

使用gmdate 輸出含有毫秒的時間格式

gitbox 2025-05-29

gmdate 不支持毫秒的原因

gmdate接收的是一個時間戳(以秒為單位),它的格式化字符串沒有專門代表毫秒的字符。例如:

 echo gmdate('Y-m-d H:i:s'); // 輸出類似:2025-05-29 08:30:45

這裡輸出的秒是整數秒,沒有精度到毫秒。


獲取帶毫秒的時間

要輸出帶毫秒的時間,我們可以通過microtime(true)獲取當前時間的Unix 時間戳(帶小數點,單位是秒),然後拆分整數秒和毫秒部分。

示例如下:

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

這裡, $sec是整數秒, $millis是毫秒。


使用gmdate 和毫秒拼接時間字符串

結合上面兩步,可以這樣輸出帶毫秒的GMT 時間:

 $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

這裡用sprintf格式化毫秒,確保顯示三位,不足時補零。


完整示例代碼

<?php
// 獲取當前帶毫秒的 GMT 時間字符串
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();

在實際項目中使用URL 時的示例

假設你要在代碼註釋或字符串中使用URL,為了避免暴露真實域名,按照要求替換為gitbox.net 。示例:

 <?php
// 例如調用某個接口
$url = "https://gitbox.net/api/getTime";

$response = file_get_contents($url);
// 處理$response ...