30

golang获取当前时间、时间戳和时间字符串及它们之间的相互转换

 4 years ago
source link: https://www.tuicool.com/articles/eMj6rmZ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

获取当前时间,类型是Go的时间类型Time

(1)

currentTime:=time.Now()     //

(2)

t2:=time.Now().Month()       //月

    t3:=time.Now().Day()         //日

    t4:=time.Now().Hour()        //小时

    t5:=time.Now().Minute()      //分钟

    t6:=time.Now().Second()      //秒

    t7:=time.Now().Nanosecond()  //纳秒
    currentTimeData:=time.Date(t1,t2,t3,t4,t5,t6,t7,time.Local) //获取当前时间,返回当前时间Time     
     fmt.Println(currentTime)       //打印结果:2017-04-11 12:52:52.794351777 +0800 CST
     fmt.Println(t1,t2,t3,t4,t5,t6)     //打印结果:2017 April 11 12 52 52
     fmt.Println(currentTimeData)    //打印结果:2017-04-11 12:52:52.794411287 +0800 CST

说明:从打印结果可以看出,time.Now()和Date()方法都可以获取当前时间,time.Now()用起来比较简单,但是Date()可以获取不同的精确值,如time.Date(t1,t2,t3,t4,t5,t6,0,time.Local)将毫秒省略,精确到秒,结果为:2017-04-11 12:52:52 +0800 CST

2、获取当前时间戳

timeUnixNano:=time.Now().UnixNano()  //单位纳秒,打印结果:1491888244752784461

3、获取当前时间的字符串格式

`` timeStr:=time.Now().Format("2006-01-02 15:04:05")  //当前时间的字符串,2006-01-02 15:04:05据说是golang的诞生时间,固定写法
     fmt.Println(timeStr)    //打印结果:2017-04-11 13:24:04
#4、它们之间的相互转化

##1) 时间戳转时间字符串 (int64 —>  string)

  ```  timeUnix:=time.Now().Unix()   //已知的时间戳
        formatTimeStr:=time.Unix(timeUnix,0).Format("2006-01-02 15:04:05")
        fmt.Println(formatTimeStr)   //打印结果:2017-04-11 13:30:39

2) 时间字符串转时间(string —> Time)

formatTime,err:=time.Parse("2006-01-02 15:04:05",formatTimeStr)
    if err==nil{
      fmt.Println(formatTime) //打印结果:2017-04-11 13:33:37 +0000 UTC
   }

3) 时间字符串转时间戳 (string —> int64)

比上面多一步,formatTime.Unix()即可

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK