How to generate random date in Go lang?

huangapple go评论87阅读模式
英文:

How to generate random date in Go lang?

问题

以上代码给出了一个时间戳,但是,如果我只想分别获取日期部分和时间部分,可以使用split()函数吗?

英文:
time.Date(2009, 11, 17, 20, 34, 58, 651387237, time.UTC)

The above code gives us a timestamp but, what if I want to fetch only the date part and the time part separately? Is it possible to use split()?

答案1

得分: 29

你可以使用math/rand来生成一个随机日期,代码如下:

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

func randate() time.Time {
    min := time.Date(1970, 1, 0, 0, 0, 0, 0, time.UTC).Unix()
	max := time.Date(2070, 1, 0, 0, 0, 0, 0, time.UTC).Unix()
	delta := max - min
	
	sec := rand.Int63n(delta) + min
	return time.Unix(sec, 0)
}

你可以在这里查看代码示例:https://play.golang.org/p/x1CK6nIO-v

英文:

You can use math/rand to generate a random date like this:

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

func randate() time.Time {
    min := time.Date(1970, 1, 0, 0, 0, 0, 0, time.UTC).Unix()
	max := time.Date(2070, 1, 0, 0, 0, 0, 0, time.UTC).Unix()
	delta := max - min
	
	sec := rand.Int63n(delta) + min
	return time.Unix(sec, 0)
}

https://play.golang.org/p/x1CK6nIO-v

huangapple
  • 本文由 发表于 2017年4月19日 20:26:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/43495745.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定