duanbiyi7319 2018-05-30 20:50 采纳率: 100%
浏览 2298
已采纳

如何设置Golang时间(以毫秒为单位)?

我在时间转换上遇到了麻烦。10秒的时间我必须把下面这些转移到 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() convert to milliseconds?

转换成毫秒,然后除以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

  • 写回答

1条回答 默认 最新

  • drbuowqe02101 2018-05-30 21:23
    关注

    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)
    }
    

    playground example

    You can replace 1e8 with int64(time.Second/10) for a possible improvement in readability.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 file converter 转换格式失败 报错 Error marking filters as finished,如何解决?
  • ¥15 ubuntu系统下挂载磁盘上执行./提示权限不够
  • ¥15 Arcgis相交分析无法绘制一个或多个图形
  • ¥15 关于#r语言#的问题:差异分析前数据准备,报错Error in data[, sampleName1] : subscript out of bounds请问怎么解决呀以下是全部代码:
  • ¥15 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型