問題描述
7 位小數計算的 UTC 時間 (UTC time with 7 decimals calculation)
我需要在 PHP 7.3 中計算 2 個 UTC 時間值與 7 位小數之間的差異
我可以簡單地執行以下操作:
val1 = 20200205120415.6513380; //first timestamp
val2 = 20200205120415.6535670; //second timestamp
$diff = $val2 ‑ $val1; //should be difference between the 2 timestamps
上述計算的值為 0.002229 . 如果我做得正確,該值以秒或微秒為單位,我能否將其轉換為 UNIX 紀元時間戳?
參考解法
方法 1:
I strongly suspect that the above times are not simple numbers; they BCD (binary coded decimal) for 2020‑02‑05‑12:04:15.6513380. You can't do simple math on these, and you'll need to parse them to convert to a unix timestamp.
Depending on your language, it may be easiest to parse these by turning them into strings and taking the first four characters as the year, the next two as the month, etc.
方法 2:
Here is my current solution for completeness.
The values on the right of the . is indeed fractional seconds. So in PHP to get the difference I did the following:
$start = 20200205120415.6513380;
$end = 20200205120415.6535670;
//get value left of . and then create datetime object to later convert to seconds
list($datetime, $usecStart) = explode(".", $start);
$startTime = date_create_from_format("YmdHis", $datetime);
list($datetime, $usecEnd) = explode(".", $end);
$endTime = date_create_from_format("YmdHis", $datetime);
//get timestamp in seconds and add franction or microseconds back
$start = $startTime‑>getTimestamp().".".$usecStart;
$end = $endTime‑>getTimestamp().".".$usecEnd;
//get difference in seconds and fraction or microseconds
echo $end ‑ $start;
Here is another way using datetime‑>diff() function:
$start = new DateTime('2020‑02‑05T12:04:15.6513380Z');
$end = new DateTime('2020‑02‑05T12:04:15.6535670Z');
$diff = $start‑>diff($end);
echo $diff‑>format('%h:%i:%s.%F');
(by Bobster101、Rob Napier、Bobster101)