Home >Backend Development >Golang >golang date to time
In the Go language, the time library can be used to process dates and times. The time library provides some functions for date and time operations, which can easily convert and calculate dates and times.
First, we need to define a variable of type time.Time to represent a certain date and time. This type contains date and time information, where date is in days and time is in nanoseconds. We can use the time.Now() function to get the current date and time:
now := time.Now()
This function returns an instance of the time.Time type.
To format a date into a string, you can use the time.Format() function. Its parameter is a format string that describes the format in which the date and time should be output. For example, the following code formats a date into a string in YYYY-MM-DD format:
now := time.Now() dateStr := now.Format("2006-01-02")
In this format string, the numeric part represents the various parts of the date and time, for example, "2006" represents the year, Because the release version of Go language is 2006. The month part is represented by "01" because it is the first month of the year, and the day part is represented by "02" because it is the second day of the month.
To convert a string to a date, you can use the time.Parse() function. It takes two parameters: date string and format string. For example, the following code converts a string in the format YYYY-MM-DD to a time:
dateStr := "2021-05-20" date, err := time.Parse("2006-01-02", dateStr) if err != nil { panic(err) }
In this example, "2006-01-02" is the format string and the date variable is time.Time An instance of type that represents a date and time.
To convert a timestamp (time in seconds) to time, you can use the time.Unix() function. It takes two parameters: timestamp and nanosecond offset. For example, the following code converts a timestamp to a time:
timestamp := 1621527891 nanoSec := 0 time := time.Unix(int64(timestamp), int64(nanoSec))
where the time.Unix() function returns an instance of the time.Time type.
To get the year, month, day, hour, minute, second and millisecond part of a time, you can call Year(), Month(), Day(), Hour(), Minute(), Second() and Nanosecond() methods. For example, the following code obtains the year, month, and day of the current time:
now := time.Now() year := now.Year() month := now.Month() day := now.Day()
In addition, the time library also provides many other functions and types, such as the Duration type (representing a period of time), the Ticker type (used for timing scheduling), Timer type (used for delayed execution), ParseDuration() function (used for parsing time period strings), etc.
In short, the time library of the Go language provides many convenient functions and types, making the processing of dates and times very simple.
The above is the detailed content of golang date to time. For more information, please follow other related articles on the PHP Chinese website!