golang獲取當前時間、時間戳和時間字符串及它們之間的相互轉換

一、獲取當前時間

     (1) currentTime:=time.Now()     //獲取當前時間,類型是Go的時間類型Timegolang

 

   (2)ide

    t1:=time.Now().Year()        //年orm

    t2:=time.Now().Month()       //月字符串

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

    t4:=time.Now().Hour()        //小時it

    t5:=time.Now().Minute()      //分鐘form

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

    t7:=time.Now().Nanosecond()  //納秒方法

 

      currentTimeData:=time.Date(t1,t2,t3,t4,t5,t6,t7,time.Local) //獲取當前時間,返回當前時間Time     im

 

       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

 

   

 

二、獲取當前時間戳

        timeUnix:=time.Now().Unix()            //單位s,打印結果:1491888244

       timeUnixNano:=time.Now().UnixNano()  //單位納秒,打印結果:1491888244752784461

 

三、獲取當前時間的字符串格式

         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

 

 

四、它們之間的相互轉化

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)

      formatTimeStr=」2017-04-11 13:33:37」

      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()便可

相關文章
相關標籤/搜索