这是一个老问题,但我注意到缺少实用的答案。
例如,我们正在使用 MavLink 协议,我们需要处理带有structure defined here 的消息。
如果我们有这个数据结构:
| Field Name |
Type |
Units |
Description |
| time_boot_ms |
uint64_t |
ms |
Timestamp (time since system boot). |
| press_abs |
float |
hPa |
Absolute pressure |
| press_diff |
float |
hPa |
Differential pressure 1 |
| temperature |
int16_t |
cdegC |
Absolute pressure temperature |
| temperature_press_diff ** |
int16_t |
cdegC |
Differential pressure temperature (0, if not available). Report values of 0 (or 1) as 1 cdegC. |
因此,我们会收到持续更新,我们需要使用 time_boot_ms 作为参考来处理这些更新,以便将它们插入数据库并与其他消息同步。
我们能做什么?
正如我们所注意到的,时间以毫秒为单位,每个对 Go 有一定经验的人都知道,由于某些未知原因,将毫秒分辨率的 Unix timestamp 转换为太复杂了time.Time。内置的time.Unix()函数只支持秒和纳秒精度。
我们如何获得毫秒精度?
好吧,我们可能会等到他们发布 Go 的 1.7 版本,或者我们必须将毫秒乘以纳秒,或者将它们分成秒和纳秒。
让我们实现第二个想法,将其分为秒和纳秒:
unixUTCtime := time.Unix(ms/int64(1000), (ms%int64(1000))*int64(1000000))
现在我们可以将它封装在 func 中,并像这样在我们的 main 中使用它:
package main
import (
"fmt"
"time"
)
const msInSecond int64 = 1e3
const nsInMillisecond int64 = 1e6
// UnixToMS Converts Unix Epoch from milliseconds to time.Time
func UnixToMS (ms int64) time.Time {
return time.Unix(ms/msInSecond, (ms%msInSecond)*nsInMillisecond)
}
func main() {
unixTimes := [...]int64{758991688, 758992188, 758992690, 758993186}
var unixUTCTimes []time.Time
for index, unixTime := range unixTimes {
unixUTCTimes = append(unixUTCTimes, UnixToMS(unixTime))
if index > 0 {
timeDifference := unixUTCTimes[index].Sub(unixUTCTimes[index-1])
fmt.Println("Time difference in ms :--->", timeDifference)
}
}
}
输出将是:
Time difference in ms :---> 500ms
Time difference in ms :---> 502ms
Time difference in ms :---> 496ms
Check in Go Playground