乐闻世界logo
搜索文章和话题

How do you use the " time " package to handle dates and times in Go?

1个答案

1

In Go, the time package provides a set of functionalities for handling dates and times. Here are several basic methods for using the time package:

1. Getting the Current Time

To obtain the current date and time, use the time.Now() function. This returns a time.Time object representing the current time.

go
now := time.Now() fmt.Println("Current time:", now)

2. Creating a Specific Time

To create a specific time point, use the time.Date() function. You must provide the year, month, day, hour, minute, second, nanosecond, and time zone.

go
date := time.Date(2022, time.November, 10, 20, 34, 58, 0, time.UTC) fmt.Println("Specified time:", date)

3. Formatting and Parsing Time

The time package enables you to format or parse time strings according to a specified format. Formatting converts a time.Time object into a string, while parsing converts a string into a time.Time object.

Formatting

go
formatted := now.Format("2006-01-02 15:04:05") fmt.Println("Formatted time:", formatted)

Parsing

go
t, err := time.Parse("2006-01-02 15:04:05", "2022-11-10 20:34:58") if err != nil { log.Fatal(err) } fmt.Println("Parsed time:", t)

4. Time Comparison

You can compare two time points to determine if they are equal, or if one precedes or follows the other.

go
isBefore := now.Before(date) isAfter := now.After(date) isEqual := now.Equal(date) fmt.Println("Is current time before specified time?", isBefore) fmt.Println("Is current time after specified time?", isAfter) fmt.Println("Is current time equal to specified time?", isEqual)

5. Time Addition and Subtraction

For adding or subtracting time, use the Add and AddDate methods. Add handles smaller units like hours and minutes, whereas AddDate handles larger units such as years, months, and days.

Adding and Subtracting Hours, etc.

go
later := now.Add(3 * time.Hour) fmt.Println("Three hours later:", later)

Adding and Subtracting Years, Months, and Days

go
earlier := now.AddDate(0, -1, 0) // Subtract one month fmt.Println("One month ago:", earlier)

These are the fundamental methods for using the time package in Go to handle dates and times. With these methods, you can easily perform tasks such as creating, manipulating, and comparing time.

2024年8月7日 17:54 回复

你的答案