go语言time包的使用

时间类型

time.Time类型表示时间。

//时间类型
func timeDemo()  {
    now := time.Now()
    fmt.Println(now)    //2019-04-20 13:52:35.226397 +0800 CST m=+0.000336111
    fmt.Println(now.Format("2006-01-02 15:04")) //2019-04-20 13:52
    year := now.Year()
    month := now.Month()
    day := now.Day()
    hour := now.Hour()
    minute := now.Minute()
    second := now.Second()
    //输出格式可以自定义
    fmt.Printf("%d,%02d,%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second) //2019,04,24 18:13:48
}

时间戳

时间戳是自1970年1月1日(08:00:00GMT)至当前时间的总毫秒数。它也被称为Unix时间戳(UnixTimestamp)。

//时间戳
func timestampDemo()  {
    now := time.Now()
    timestamp := now.Unix()
    fmt.Println(timestamp)  //1556101693
}

time.Unix()函数将时间戳转为时间格式。

func timestampDemo2(timestamp int64) {
    timeObj := time.Unix(timestamp, 0) //将时间戳转为时间格式
    fmt.Println(timeObj)    //2019-04-24 18:30:12 +0800 CST
    year := timeObj.Year()     //年
    month := timeObj.Month()   //月
    day := timeObj.Day()       //日
    hour := timeObj.Hour()     //小时
    minute := timeObj.Minute() //分钟
    second := timeObj.Second() //秒
    fmt.Printf("%d-%02d-%02d %02d:%02d:%02d\n", year, month, day, hour, minute, second) //2019-04-24 18:30:12
}

时间间隔

Duration类型代表两个时间点之间经过的时间,以纳秒为单位。
const (
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
)

定时器

time.Tick(时间间隔)来设置定时器。

//定时器,每隔1s打印下i
func tickDemo() {
    ticker := time.Tick(time.Second)
    for i := range ticker{
        fmt.Println(i)
    }
}

时间格式化

Go语言中格式化时间模板不是常见的Y-m-d H:M:S而是使用Go的诞生时间2006年1月2号15点04分(记忆口诀为2006 1 2 3 4 5)。

//时间格式化
func formatDemo() {
    now := time.Now()
    // 格式化的模板为Go的出生时间2006年1月2号15点04分
    fmt.Println(now.Format("2006-01-02 15:04:05"))  //2019-04-24 18:37:59
    fmt.Println(now.Format("2006/01/02 15:04"))
    fmt.Println(now.Format("15:04 2006/01/02"))
    fmt.Println(now.Format("2006/01/02"))
}

猜你喜欢

转载自www.cnblogs.com/aresxin/p/go-yu-yantime-bao-de-shi-yong.html