How to Obtain Millisecond‑Precision Timestamps in PHP: 13‑Digit, Float, and Custom 14‑Digit Formats
This article demonstrates three PHP techniques for obtaining millisecond‑precision timestamps—13‑digit integer, floating‑point value, and a custom 14‑digit format—providing full code examples and usage illustrations. It also shows how to integrate the timestamp into request data structures for payment APIs.
The tutorial explains how to generate timestamps with millisecond precision in PHP, covering three different approaches.
First method: 13‑digit integer timestamp
<code>/**
* Get timestamp in milliseconds (13 digits)
* @return bool|string
*/
public static function getMillisecond() {
list($msec, $sec) = explode(' ', microtime());
$msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
return $msectimes = substr($msectime, 0, 13);
}
</code>Calling the method and printing the result yields a 13‑digit timestamp accurate to the millisecond.
Second method: floating‑point timestamp
<code>/**
* Timestamp – precise to milliseconds
* @return float
*/
public static function getMillisecond() {
list($t1, $t2) = explode(' ', microtime());
return (float)sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
}
</code>Example usage:
<code>// timestamp
$_t = self::getMillisecond();
dd($_t);
</code>Third method: 14‑digit format (YYYYMMDDHHIISS + 3‑digit milliseconds)
<code>/**
* Year‑month‑day, hour‑minute‑second + 3‑digit milliseconds
* @param string $format
* @param null $utimestamp
* @return false|string
*/
public static function ts_time($format = 'u', $utimestamp = null) {
if (is_null($utimestamp)) {
$utimestamp = microtime(true);
}
$timestamp = floor($utimestamp);
$milliseconds = round(($utimestamp - $timestamp) * 1000);
return date(preg_replace('`(?<!\\)u`', $milliseconds, $format), $timestamp);
}
</code>Example usage in a payment request array:
<code>public static function getAllInfo($reqData, PayMerchant $payConf) {
$data = array(
'mchntCode' => $payConf['business_num'],
'channelCode' => $reqData['bank'],
'mchntOrderNo' => $reqData['order'],
'orderAmount' => $reqData['amount'] * 100,
'clientIp' => request()->ip(),
'subject' => 'goodsName',
'body' => 'goodsName',
'notifyUrl' => $reqData['ServerUrl'],
'pageUrl' => $reqData['returnUrl'],
'orderTime' => date('YmdHis'),
'description' => $reqData['order'],
'orderExpireTime'=> date('YmdHis', time() + 300),
'ts' => self::ts_time('YmdHisu'),
);
dd($data);
}
</code>The article also includes screenshots illustrating the output of each method.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.