Go language time library, time and date related operation methods

time library

Core library for working with times, dates and timezones. In actual development, it is often necessary to deal with time, such as recording logs, processing time differences, calculating time intervals, and so on. Therefore, it is very important for Go developers to master how to use the time library.

In Go language, time is expressed as time.Time type, date is expressed as time.Time type or time.Date type, and time zone is expressed as time.Location type. The concepts of these types and how to use them are described in detail below.

time

In Go language, time is represented as time.Time type. The time.Time type is a structure that contains two fields: a large integer with fields such as century and second and a small integer, which represent the year of the time and the fractional part of the time respectively.

You can use the functions in the time package to get the current time, specify a time, or add or subtract time. Here are some commonly used time manipulation functions:

time.Now(): returns the current local time
time.Parse(layout, str): parses the string str into the time of the specified format layout
time.Add(d time.Duration): returns the current time plus the given time interval d The result of
time.Sub(t, u time.Time): returns the time interval of time t minus time u

date

The date is expressed as time.Time type or time.Date type. Among them, the time.Time type represents the complete time, including information such as hours, minutes, and seconds; while the time.Date type only represents the date part, not including the time part.

You can use the functions in the time package to get the month and day of the specified date, or to add and subtract dates. Here are some commonly used date manipulation functions:

time.Month(month int): Returns the string representation of the specified month
time.Day(): Returns the number of days in the current date
time.AddDate(year int, month int, day int): Returns the specified year, month and day plus the given The result of a fixed time interval
time.Sub(t, u time.Time): returns the time interval of time t minus time u

Time zone

Time zones are represented as time.Location types. The time.Location type is a structure that contains a string indicating the identifier of the time zone and some fields, such as seconds and bias.

You can use the functions in the time package to get the offset of the specified time zone or to convert the time zone. Here are some commonly used time zone manipulation functions:

time.Local: Indicates the local time zone
time.UTC: Indicates the UTC time zone
time.LoadLocation(name string): Returns the time.Location type object of the specified time zone name
time.In(loc time.Location, t time.Time): Returns the specified time zone The time t is converted to the result of the target time zone loc

function

time.Now(): Returns the current local time.
time.Parse(layout, str): Parse the string str into the time of the specified format layout.
time.Add(d time.Duration): Returns the current time plus the result of the given time interval d.
time.Sub(t, u time.Time): Returns the time interval of time t minus time u.
time.Sub(t, u time.Time) time.Duration: Returns the time interval of time t minus time u.
time.AddDate(years int, months int, days int) time.Time: Add time based on year, month, day increments.
time.Since(t time.Time) time.Duration: Returns the time interval from t to now.
time.Until(u time.Time) time.Duration: Returns the time interval from now to u.
t.After(u): If t is after u, return true, otherwise return false.
t.Before(u): If t is before u, return true, otherwise return false.
time.Unix(sec int64, nanosec int64) time.Time: Convert a Unix timestamp to a time object.
time.ParseUnix(str string, layout string) (sec int64, nanosec int64, err error): Parse the time string into a Unix timestamp in the specified format.
time.Set(sec int64, n int) time.Time: Set the current time to the given number of seconds and nanoseconds.
time.Sleep(d Duration): to allow the program to pause for a period of time during execution.
time.Hour() int: Returns the integer value of the current hour.
time.Minute() int: Returns the integer value of the current minute.
time.Second() int: Returns the integer value of the current second.
time.Nanosecond() int: Returns the integer value of the current nanosecond.
time.Weekday() time.Weekday: Returns the enumeration value of the current day of the week.
time.Day(): Returns the day number of the current date.
time.Month() time.Month: Returns the enumeration value of the current month.
time.Year() int: Returns the integer value of the current year.
time.Date(year int, month time.Month, day, hour, min, sec, nanosec int, loc *time.Location) time.Time: Return the local time object of the specified time.
time.isleap(year int) bool: Determine whether the given year is a leap year.
time.UnixNano() int64: Returns the nanosecond value of the current time.
time.Duration() time.Duration: Returns the number of nanoseconds from 0:00:00 to the present.
time.ParseDuration(str string) (time.Duration, error): Parse a time interval string into a time interval.
time.ParseInLocation(layout string, value string, loc *time.Location) (time.Time, error): According to the format and time value, parse the time and specify the time zone.
time.StartOfDay(): Returns the start time of the current day.
time.EndOfDay(): Returns the end time of the current day.
time.StartOfWeek(): Returns the Monday of the week of the current date.
time.EndOfWeek(): Returns the Sunday of the week of the current date.
time.StartOfMonth(): Returns the start time of the current month.
time.EndOfMonth(): Returns the end time of the current month.
time.StartOfYear(): Returns the start time of the current year.
time.EndOfYear(): Returns the end time of the current year.
time.Sunday: Returns the enumeration value of the day of the week, 0 is Sunday, 6 is Saturday, and so on.
time.ParseDuration(str string) (time.Duration, error): Parse a time interval string into a time interval.
time.Hour() time.Duration: Returns the time interval for the current hour.
time.Minute() time.Duration: Returns the time interval in the current minute.
time.Second() time.Duration: Returns the time interval in the current second.
time.Nano() time.Duration: Returns the current nanosecond interval.
time.ANSIC() string: Returns the datetime corresponding to the ANSI C string representation.
time.FixedZone(name string, offset int) *time.Location: Return a fixed time zone object.
time.LoadLocation(name string) (*time.Location, error): Load a time zone object.
time.In(t time.Time, loc *time.Location) time.Time: Convert the time t to the time in the specified time zone.

type

Time: Indicates a point in time, including date and time.
Date: Indicates the date, including year, month, and day.
LocalTime: Indicates the local time.
Location: Indicates the time zone.
ZeroTime: Indicates the zero point of the time, that is, 00:00:00 UTC on January 1, 1970.
Duration: It represents a period of time, which can be in units of nanoseconds, microseconds, milliseconds, seconds, etc.

example

code 1

package main

import (
	"fmt"
	"time"
)

func main() {
	// 获取当前时间
	currentTime := time.Now()
	fmt.Println("Current Time:", currentTime)

	// 暂停程序执行 5 秒钟
	fmt.Print("Waiting for 5 seconds: ")
	for i := 0; i < 5; i += 1 {
		time.Sleep(time.Second)
		fmt.Print(".")
	}
	fmt.Println()

	// 获取指定日期的本地时间
	year := 2023
	month := time.March
	day := 17
	hour := 0
	minute := 0
	second := 0
	nano := 0
	loc := &time.Location{}
	date := time.Date(year, month, day, hour, minute, second, nano, loc)
	fmt.Println("Date:", date)

	// 将时间字符串转换为时间对象
	layout := "2006-01-02 15:04:05"
	value := "2023-03-23 08:30:00"
	parsedTime, err := time.Parse(layout, value)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println("Parsed Time:", parsedTime)

	// 格式化时间对象为字符串
	format := "2006-01-02 15:04:05 MST"
	formattedTime := parsedTime.Format(format)
	fmt.Println("Formatted Time:", formattedTime)

	// 计算两个时间之间的时间差
	t2 := time.Now()
	diff := t2.Sub(parsedTime)
	fmt.Println("Time Difference:", diff)

	// 将时间对象转换为UTC时区
	utcTime := parsedTime.UTC()
	fmt.Println("UTC Time:", utcTime)

	// 将时间对象转换为本地时区
	localTime := parsedTime.In(time.Local)
	fmt.Println("Local Time:", localTime)
}

output:

Current Time: 2023-08-01 20:15:11.0034059 +0800 CST
Waiting for 5 seconds: .....
Date: 2023-03-17 00:00:00 +0000 UTC
Parsed Time: 2023-03-23 08:30:00 +0000 UTC
Formatted Time: 2023-03-23 08:30:00 UTC
Time Difference: 3147h45m16.0065551s
UTC Time: 2023-03-23 08:30:00 +0000 UTC
Local Time: 2023-03-23 16:30:00 +0800 CST

code 2

package main

import (
	"fmt"
	"time"
)

func main() {
	// 解析时间字符串为时间对象
	layout := "2006-01-02 15:04:05"
	strTime := "2023-03-23 12:30:00"
	t, err := time.Parse(layout, strTime)
	if err != nil {
		fmt.Println("时间解析错误:", err)
	}
	fmt.Println("解析后的时间:", t)

	// 时间加减
	d := time.Duration(24) * time.Hour
	t = t.Add(d)
	fmt.Println("加上一天的时间:", t)

	u := t.Add(-d)
	fmt.Println("减去一天的时间:", u)

	// 时间间隔
	diff := t.Sub(u)
	fmt.Println("加上一天和减去一天的时间间隔:", diff)

	// 时间格式化输出
	layout = "2006-01-02"
	t = time.Now()
	formattedTime := t.Format(layout)
	fmt.Println("格式化后的时间:", formattedTime)

	// 时间转换为Unix时间戳
	unixTime := t.Unix()
	fmt.Println("Unix时间戳:", unixTime)

	// 时间比较
	t1 := time.Now()
	t2 := t1.Add(time.Hour)
	diff = t2.Sub(t1)
	fmt.Println("t2 - t1 =", diff)
	fmt.Println("t1 < t2:", t1.Before(t2))
	fmt.Println("t2 > t1:", t2.After(t1))
}

output:

Parsed time: 2023-03-23 ​​12:30:00 +0000 UTC
plus one day: 2023-03-24 12:30:00 +0000 UTC
minus one day: 2023-03-23 ​​12: 30:00 +0000 UTC
plus and minus one day Interval: 24h0m0s
Formatted time: 2023-08-01
Unix timestamp: 1690892235
t2 - t1 = 1h0m0s
t1 < t2: true
t2 > t1: true


Summarize

This article introduces the time library in Go language, including related concepts and usage methods of time, date and time zone. By mastering this knowledge, you can better handle issues related to time, date, and time zone, and improve development efficiency.

Guess you like

Origin blog.csdn.net/boysoft2002/article/details/132031566