golang 日期常用方法整理

2019-07-16  本文已影响0人  louhangfei
//获取当前时间    
        now := time.Now()
    fmt.Println("now", now) 
//now 2019-07-16 18:16:12.457678344 +0800 CST m=+0.000443035

    // time转化为string类型
    _now :=now.String()
    fmt.Println("_now", _now) 
//_now 2019-07-16 18:16:12.457678344 +0800 CST m=+0.000443035


    // 转化为string类型,也可以用Format。
// 用Format更加可控,可以指定输出的日期时间格式
    _n1 := now.Format("2006-01-02")
    fmt.Println("_n1", _n1) //_n1 2019-07-16

    _n2 := now.Format("2006-01-02 15:04")
    fmt.Println("_n1", _n2) //_n1 2019-07-16 18:16



    // 获取年月日
    year, month, day :=now.Date()
    fmt.Println("year", year, ",month",month, "day,",day)
//year 2019 ,month July day, 16


    //string类型如何转化为time类型
    x := "2018-12-27 18:44:55"
    p, _ := time.Parse("2006-01-02 15:04:05", x)
    fmt.Println("p", p) //p 2018-12-27 18:44:55 +0000 UTC


    // 但是由String方法转化来的_now参数,
    // 无法直接转化为时间类型,
    //得到的t是0001-01-01 00:00:00 +0000 UTC, 
    //因为它不符合2006-01-02 15:04:05格式
    t, _:= time.Parse("2006-01-02 15:04:05", _now)
    fmt.Println("t", t) // t 0001-01-01 00:00:00 +0000 UTC


    // time类型转化为时间戳,注意是在实例上调用Unix方法
    _u :=now.Unix()
    fmt.Println("unix ", _u) 
// unix  1563272172


    // 时间戳如何转化为time类型,注意是在time结构体上调用Unix方法
    u2 :=time.Unix(_u,0)
    fmt.Println("u2", u2) 
// u2 2019-07-16 18:16:12 +0800 CST


上一篇下一篇

猜你喜欢

热点阅读