在 Go 中生成随机时间戳

mxp*_*usb 6 random time go

我想生成最近 3 年内的随机时间戳,并使用以下格式打印出来:%d/%b/%Y:%H:%M:%S %z

这是我现在所拥有的:

package main

import (
    "strconv"
    "time"
    "math/rand"
    "fmt"
)

func randomTimestamp() time.Time {
    randomTime := rand.Int63n(time.Now().Unix() - 94608000) + 94608000

    randomNow, err := time.Parse("10/Oct/2000:13:55:36 -0700", strconv.FormatInt(randomTime, 10))
    if err != nil {
        panic(err)
    }

    return randomNow
}

func main() {
    fmt.Println(randomTimestamp().String())
}
Run Code Online (Sandbox Code Playgroud)

这总是抛出:panic: parsing time "...": month out of range。如何生成给定范围的随机时间戳,然后使用标准库将其转换为我想要的字符串格式?

mat*_*mc3 4

不要使用 time.Parse。你有一个 Unix 时间,而不是一个时间字符串。请改用该Unix()方法。https://golang.org/pkg/time/#UnixAdd您还可以选择一个最小时间值,例如 1/1/1900,并使用Time 方法并传递Duration您使用 Ticks() 方法创建的时间,向时间添加随机的秒数持续时间。https://golang.org/pkg/time/#Duration

这是 Go Playground 链接。请记住,Go Playground 不支持实际的随机性。https://play.golang.org/p/qYTpnbml_N

package main

import (
    "time"
    "math/rand"
    "fmt"
)

func randomTimestamp() time.Time {
    randomTime := rand.Int63n(time.Now().Unix() - 94608000) + 94608000

    randomNow := time.Unix(randomTime, 0)

    return randomNow
}

func main() {
    fmt.Println(randomTimestamp().String())
}
Run Code Online (Sandbox Code Playgroud)