go - Golang 时间(以分秒为单位)
问题描述
我在将 time.Time 转换为 Deciseconds 时遇到问题。我基本上必须将以下内容移植到 Golang
Deciseconds fits into 36 bits with enough precision to record a user's consent action timing. Javascript: Math.round((new Date()).getTime()/100)
我试过使用 Go / golang time.Now().UnixNano() 转换为毫秒?
转换为毫秒,然后除以 100。这会产生错误的时间戳。我敢打赌这是我的一个愚蠢的错误,但我只是想得到一些反馈
这是读取我尝试提交的时间戳的方法
// ReadTime reads the next 36 bits representing the epoch time in deciseconds
// and converts it to a time.Time.
func (r *ConsentReader) ReadTime() time.Time {
var ds = int64(r.ReadBits(36))
return time.Unix(ds/dsPerS, (ds%dsPerS)*nsPerDs).UTC()
}
https://github.com/LiveRamp/iabconsent/blob/328e761006ce2652bc8c0daee614381d7565c05e/parse.go#L34
我正在设置日期
func (b bit) setDateToDeciseconds(startInclusive int, size int, t time.Time) {
deciseconds := int32(t.Unix() / 1000)
b.setNumberInt32(startInclusive, size, deciseconds)
}
func (b bit) setNumberInt32(startInclusive int, size int, to int32) {
for i := size - 1; i >= 0; i-- {
index := startInclusive + i
byteIndex := index / 8
shift := uint((byteIndex+1)*8 - index - 1)
b[byteIndex] |= byte((to % 2) << shift)
to /= 2
}
}
我不断得到看起来像的日期时间
time.Now() ->1970-01-02 18:26:11.4 +0000 UTC
解决方案
Use these functions to convert a time.Time to and from deciseconds since the epoch.
func toDeci(t time.Time) int64 {
return t.UnixNano() / 1e8
}
func fromDeci(t int64) time.Time {
return time.Unix(0, t*1e8)
}
You can replace 1e8
with int64(time.Second/10)
for a possible improvement in readability.
推荐阅读
- c# - 如何在 StatusStripLabel 上显示坐标
- java - 从 JSON 中检索整数数据并显示在单独的活动中
- java - 从 Java/Kotlin 插入的 H2 和 MySQL 数据库中的 DATETIME 值不匹配
- ios - 将字符串拆分为子数组数组
- c# - 如何根据 JObject 中的子属性值选择父属性值
- python - 如何从 excel 列中搜索文本单元格并将其打印到新的 excel 文档中?
- c# - c# - People API 不返回电子邮件地址
- java - 未找到适用于 ucanaccess 的驱动程序
- tfs - 使用本地 TFS 发布管理器实施 Azure DevOps 服务
- android - 将 VSTO Outlook 加载项移植到移动设备