golang gets current time, timestamp and time string and conversion between them

1. Get the current time
     (1) currentTime:=time.Now() //Get the current time, the type is Go's time type Time
    t1:=time.Now().Year() //year
    t2:=time.Now().Month() //month
    t3:=time.Now().Day() //Day
    t4:=time.Now().Hour() //hour
    t5:=time.Now().Minute() //minute
    t6:=time.Now().Second() //seconds
    t7:=time.Now().Nanosecond() //Nanosecond
      currentTimeData:=time.Date(t1,t2,t3,t4,t5,t6,t7,time.Local) //Get the current time and return the current time Time
       fmt.Println(currentTime) //Print result: 2017-04-11 12:52:52.794351777 +0800 CST
      fmt.Println(t1,t2,t3,t4,t5,t6) //Print result: 2017 April 11 12 52 52
      fmt.Println(currentTimeData) //Print result: 2017-04-11 12:52:52.794411287 +0800 CST
Note: As can be seen from the printed results, both time.Now() and Date() methods can obtain the current time. Time.Now() is relatively simple to use, but Date() can obtain different precise values, such as time.Date (t1, t2, t3, t4, t5, t6, 0, time.Local) omit milliseconds, accurate to seconds, the result is: 2017-04-11 12:52:52 +0800 CST
2. Get the current timestamp
        timeUnix:=time.Now().Unix() //Unit s, print result: 1491888244
       timeUnixNano:=time.Now().UnixNano() //unit in nanoseconds, print result: 1491888244752784461
3. Get the string format of the current time
         timeStr:=time.Now().Format("2006-01-02 15:04:05") //The string of the current time, 2006-01-02 15:04:05 is said to be the birth time of golang, fixed spelling
         fmt.Println(timeStr) //Print result: 2017-04-11 13:24:04
4. Mutual transformation between them
1) Timestamp to time string (int64 —> string)
        timeUnix:=time.Now().Unix() // Known timestamp
        formatTimeStr:=time.Unix(timeUnix,0).Format("2006-01-02 15:04:05")
        fmt.Println(formatTimeStr) //Print result: 2017-04-11 13:30:39
   2) Time string to time (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) //Print result: 2017-04-11 13:33:37 +0000 UTC
   3) Time string to timestamp (string —> int64)
          One more step than the above, formatTime.Unix() can

Leave a Reply

Your email address will not be published.