In the Go language, there are many ways to set the hour of a date (date), the most common of which is to operate through the time
package. time
The package provides many functions for handling time and date operations. In this article, we will go into more depth on this basis.
In the Go language, you first need to create a time object. You can use the time.Now()
function to get the current time and store it as a time object. For example, the following code will get the current time and store it in the now
variable:
now := time.Now()
We can easily print out the various parts of the time, such as year, month, date, etc. wait. For example, the following code will print out the hour of the current time:
hour := now.Hour() fmt.Println(hour)
If you want to change the hour to another value, you can use the time.Date()
function to create a new time object. For example, the following code will create a new time object with the hour set to 15:
newTime := time.Date(now.Year(), now.Month(), now.Day(), 15, now.Minute(), now.Second(), now.Nanosecond(), now.Location())
In the time.Date()
function, you need to pass the year, month, date, hour , minutes, seconds, and nanoseconds to create a new date and time. You can then verify that this has changed by printing the hour of the new time.
newHour := newTime.Hour() fmt.Println(newHour)
At this point 15 will be output, proving that our code has successfully changed the hour to 15.
In addition, the time
package also provides a time.Parse()
function, which can convert a time string into a time object. For example, the following code can convert a string into a time object:
t, err := time.Parse("2006-01-02 15:04:05", "2021-09-01 15:30:00") if err != nil { panic(err) }
In the time.Parse()
function, the first parameter is the time layout string, and the second parameter Is the time string that needs to be converted. The function returns the converted time object and possible errors.
Finally, you need to pay attention to the time zone issue of time. By default, time objects in the Go language are represented using the UTC (Coordinated Universal Time) time zone. The time zone setting for a time can be changed by passing the time zone name in the time.LoadLocation()
function. For example, the following code sets the time zone of the time object to China Standard Time:
location, err := time.LoadLocation("Asia/Shanghai") if err != nil { panic(err) } newTime = newTime.In(location)
where "Asia/Shanghai" is the time zone name of China Standard Time.
In short, changing the number of hours in a datetime in Go language can be done by creating a new time object and specifying the new number of hours. At the same time, you need to pay attention to time zone issues to avoid erroneous results.
The above is the detailed content of golang set date hour. For more information, please follow other related articles on the PHP Chinese website!