Standard library in golang

Time type

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

func main() {
	current := time.Now()
	fmt.Println(current)
	// 2021-11-26 16:13:54.3960877 +0800 CST m=+0.011114601

	// Convert time type to string type
	strCurrent := current.Format("2006-01-02 15:04:05")
	fmt.Println(strCurrent)  // 2021-11-26 16:18:23 +0000 UTC

	// Convert string type to time type
	timeCurrent, _ := time.Parse("2006-01-02 15:04:05", strCurrent)
	fmt.Println(timeCurrent)  // 2021-11-26 16:18:23 +0000 UTC

	// Get a single int value in month, day, hour, minute and second. Month is the month type and month is the user-defined int type
	year := current.Year()
	month := current.Month()
	day := current.Day()
	hour := current.Hour()
	minute := current.Minute()
	second := current.Second()
	fmt.Printf("%d-%2d-%2d %2d:%2d:%2d\n", year, month, day, hour, minute, second)
	// 2021-11-26 16:13:54

}

time stamp

The timestamp is the total number of milliseconds from January 1, 1970 (08:00:00GMT) to the current time. It is also called Unix timestamp.

  1. The example code of obtaining timestamp based on time object is as follows:
func main() {
	now := time.Now()
	timestamp1 := now.Unix()  // second
	timestamp2 := now.UnixMilli()  // millisecond
	timestamp3 := now.UnixMicro()  // Microsecond
	timestamp4 := now.UnixNano()  // nanosecond

	fmt.Println(timestamp1)  // 1637915082
	fmt.Println(timestamp2)
	fmt.Println(timestamp3)
	fmt.Println(timestamp4)  // 1637915082773954700

}

  1. The timestamp can be converted to time format using the time.Unix() function.
func main() {
	now := time.Now()
	fmt.Println(now)  // 2021-11-26 16:31:22.4630069 +0800 CST m=+0.011961601
	timestamp1 := now.Unix()  // Timestamp seconds

	current := time.Unix(timestamp1, 0)  // Convert timestamp to time format
	fmt.Println(current)  // 2021-11-26 16:30:53 +0800 CST

}

Time operation

Add

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

func main() {
	now := time.Now()
	ret := now.Add(time.Hour + 30 * time.Minute)  // Calculate the time after an hour and a half
	fmt.Println(ret)
}

Sub

Find the difference between two times:

func main() {
	now := time.Now()
	endTime := now.Add(time.Hour + 30 * time.Minute)  // Calculate the time after an hour and a half

	duration := endTime.Sub(now)  // Calculate time difference
	fmt.Println(duration)  // Output: 1h30m0s
}

Returns a time period t-u. If the result exceeds the maximum / minimum value that Duration can represent, the maximum / minimum value is returned. To get the time point t-d (d is Duration), use t.Add(-d).

Equal

func main() {
	now := time.Now()
	endTime := now.Add(time.Hour + 30 * time.Minute)  // Calculate the time after an hour and a half
	now2 := time.Now()

	// Compare whether the two times are equal
	boo := endTime.Equal(now)  
	boo2 := now2.Equal(now)
	fmt.Println(boo, boo2)  // false true
}

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.

Before

func main() {
	now := time.Now()
	end := now.Add(time.Second)

	boo1 := now.Before(end)
	fmt.Println(boo1)  // true

	boo2 := end.Before(now)
	fmt.Println(boo2)  // false
}

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

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.

timer

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

  1. Method 1:
func main() {
	// Use the time.Tick interval to set the timer. The essence of the timer is a channel
	ticker := time.Tick(time.Second)  // Define a timer with an interval of 1 second
	for i := range ticker {
		fmt.Println(i.Format("2006-01-02 15:04:05"))  // Perform a task every second
	}
}

Output results:
2021-11-29 10:01:36
2021-11-29 10:01:37
2021-11-29 10:01:38

  1. Method 2:
func main() {
	// Use the time.Tick interval to set the timer. The essence of the timer is a channel
	ticker := time.NewTicker(time.Second * 2)
	for i := range ticker.C {
		fmt.Println(i.Format("2006-01-02 15:04:05"))
	}
}

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 on January 2, 2006 (the memory formula is 2006 1 2 3 4). Maybe this is the romance of technicians.

Add: if you want to format it as 12 hour mode, you need to specify PM.

func main() {
	now := time.Now()
	fmt.Println(now.Format("2006-01-02 15:04:05 Mon Jan"))  // 24-hour system
	// 2021-11-29 10:17:00 Mon Nov
	fmt.Println(now.Format("03:04:05 2006/01/02 PM Mon Jan"))  // 12 hour system
	// 10:17:00 2021/11/29 AM Mon Nov
	fmt.Println(now.Format("2006-01-02"))
	// 2021-11-29
}

Time to parse string format

func main() {
	// Time to parse string format
	now := time.Now()
	fmt.Println(now)
	// Load time zone
	loc, err := time.LoadLocation("Asia/Shanghai")
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	// Parses the string time in the specified time zone and format
	timeObj, err := time.ParseInLocation("2006/01/02 15:04:05", "2021/11/28 23:59:59", loc)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	fmt.Println(timeObj)
	fmt.Println(now.Sub(timeObj))
}

Output results:
2021-11-29 10:39:02.8339716 +0800 CST m=+0.010589201
2021-11-28 23:59:59 +0800 CST
10h39m3.8339716s

Posted by Shendemiar on Sun, 28 Nov 2021 19:09:02 -0800