Fundamentals of Go language (11)

Posted by rodneykm on Tue, 28 Dec 2021 19:40:36 +0100

11, time standard package

The time package provides functions for time display and measurement. The Gregorian calendar is used for the calculation of the 8 calendar.

11.1 time type

time. The time type represents time. We can use time The now() function obtains the current time object, and then obtains the information such as year, month, day, hour, minute and second of the time object. The example code is as follows:

func main() {
  now := time.Now()      //get SysTime
  fmt.Println("Now the time is:", now) 
  //The current time is: 2021-08-04 18:02:52.864717 +0800 CST m=+0.002099601
  year := now.Year()
  month := now.Month()
  day := now.Day()
  hour := now.Hour()
  minute := now.Minute()
  second := now.Second()
  fmt.Printf("Now:%d year%d month%d day%d Time%d branch%d second", year, month, day, hour, minute, second)
  //Now it is: 18:5:26 on August 4, 2021
}

11.2 time stamp

Use time Unix() function can convert time war to time format.

func main() {
  now := time.Now() //get SysTime
  fmt.Println("Now the time is:", now)
  //The current time is: 2021-08-04 18:14:22.4631104 +0800 CST m=+0.002645001
  fmt.Println(now.Unix())   //Timestamp 1628072062 seconds
  fmt.Println(now.UnixNano()) //Timestamp 1628072062463110400 nanoseconds
  now2 := time.Unix(now.Unix(), 0)
  fmt.Println(now2) //2021-08-04 18:14:22 +0800 CST
}

11.3 time interval

The Duration type represents the elapsed time between two time points, in nanoseconds. The longest period that can be expressed is about 290 years.

For example: time Duration means 1 nanosecond, time Second means 1 second.

const (
  Nanosecond  Duration = 1
  Microsecond     = 1000 * Nanosecond
  Millisecond      = 1000 * Microsecond
  Second        = 1000 * Millisecond
  Minute        = 60 * Second
  Hour         = 60 * Minute
}

11.4 time operation

11.4. 1. Add add

In the daily coding process, you may encounter the requirement of time + time interval. The time object of Go language provides the Add method.

func main() {
  now := time.Now() //get SysTime
  fmt.Println("Now the time is:", now)
  //The current time is: 2021-08-04 18:25:46.0697561 +0800 CST m=+0.002079701
  next := now.Add(time.**Hour** * 2)
  fmt.Println("The time after two hours is:",next)
  //Two hours later: 2021-08-04 20:25:46.0697561 +0800 CST m=+7200.002079701
}

14.4. 2. Time difference Sub

func (t Time) Sub(u Time) Duration {
}

Find the difference between two times and return a time period t-u. If the result exceeds Duration Maximum value that can be represented/Minimum value, the maximum value will be returned/Minimum value. To get a point in time t-d (d by Duration),have access to t,Add(-d). 

func main() {
  parse, err := time.Parse("2006-01-02 15:04:05.000", "2021-08-04 18:52:17.723")
  if err == nil {
   r := time.Now().UTC()
   fmt.Println(r)//2021-08-04 11:29:17.9214356 +0000 UTC
   fmt.Println(parse)//2021-08-04 18:52:17.723 +0000 UTC
   parse = parse.UTC()
   duration := r.Sub(parse)
   fmt.Println(duration)//-7h22m59.8015644s
  }else {
   fmt.Println("Time conversion error:",err)//2021-08-04 18:52:17.723 +0000 UTC
  }
}

14.4. 3. Is the time Equal

func (t Time) Equal(u Time) bool

To judge whether the two times are the same, the influence of time zone will be considered, so the time of different time zone standards can also be compared correctly. This method is different from t==u. this method also compares location and time zone information,

14.4. 4. Is the time Before

func (t Time) Before(u Time) bool

If the time point represented by t is before u, it returns true; Otherwise, false is returned.

14.4. 5. Is the time After

func (t Time) After(u Time) bool

If the time point represented by t is after u, it returns true; Otherwise, false is returned.

14.4. 6. Timer

Use time Tick (time interval) to set the timer. The timer is essentially a channel

func main() {
  ticker := time.Tick(time.**Second**) //Define a timer with an interval of 1 second
  for i := range ticker {
   fmt.Println(i) //Tasks executed every second
  }
}

14.4. 7. Time formatting

The time type has its own Format method. It should be noted that the Format time template in Go language is not the common Y-m-d H:M:S, but uses the birth time of Go at 15:04:05.000 seconds on January 2, 2006 (the memory formula is 200612345). If you want to Format it as 12 hour mode, specify PM

func main() {
  now := time.Now()
  //The formatted template is Go's birth time at 15:04:05 on January 2, 2086 Mon Jan
  fmt.Println(now.Format("2006-01-02 15:04:05.000 Mon Jan"))  //24-hour 2021-08-04 18:44:36.413 Wed Aug
  fmt.Println(now.Format("2006-01-02 03:04:05.000 Mon Jan"))  //12 hour system 2021-08-04 06:44:36.413 Wed Aug
  fmt.Println(now.Format("2006 January 2, 2015 15:04:05.000 second Mon Jan")) //August 4, 2021 18:44:36.413 Wed Aug
  fmt.Println(now.Format("2006/01/02"))  //2021/08/04
  fmt.Println(now.Format("03:04:05.000"))  //06:44:36.413
  fmt.Println(now.Format("2006-01-02 03:04:05.000"))  //2021-08-04 06:44:36.413
}

14.4. 8. Convert string to timestamp

func main() {
  parse, err := time.Parse("2006-01-02 15:04:05.000", "2021-08-04 18:52:17.723")
  if err == nil {
   fmt.Println(parse)
  }else {
   fmt.Println("Time conversion error:",err)//2021-08-04 18:52:17.723 +0000 UTC
  }
}

14.5,sleep()

func main() {
  time.Sleep(1000)
  fmt.Println("hello")
  n := 1000
  time.Sleep(time.Duration(n))
  fmt.Println("world")
}

14.6 time zone correlation

func main() {
  now := time.Now() //Local time
  fmt.Println(now)//2021-08-04 19:54:21.8713356 +0800 CST m=+0.002121301
  //This time tomorrow
  //Take the time to parse a string format according to the specified format
  parse, err2 := time.Parse("2006-01-02 15:04:05", "2021-08-04 14:41:50")
  if err2 == nil {
   fmt.Println("The resolution time is:", parse)//Resolution time: 2021-08-04 14:41:50 +0000 UTC
  } else {
   fmt.Println("Time resolution failed:",err2)
  }
  //Take and parse the time in a string format according to the time zone and format of Dongba district
  //Load time zone based on string
  loc, err := time.LoadLocation("Asia/Shanghai")
  if err == nil {
   fmt.Println("The local time zone is:", loc)//The local time zone is Asia/Shanghai
  } else {
   fmt.Println("Time zone conversion failed:",err)
  }
  parse, err2 = time.ParseInLocation("2006-01-02 15:04:05", "2019-08-04 14:41:50", loc)
  if err2 == nil {
   fmt.Println("The local time of resolution is:", parse)//The local time of parsing is: 2019-08-04 14:41:50 +0800 CST
  } else {
   fmt.Println("Local time resolution failed:",err2)
  }
}

Topics: Go