In Go, there are several ways to compare dates and times. Here's how you can achieve it:
Using the time Package:
The time package offers methods to work with time information, including comparison. Time instants can be compared using Before, After, and Equal methods. You can also use the Sub method to subtract two instants, resulting in a Duration. The Add method combines a Time and a Duration, producing a new Time.
Example:
import ( "fmt" "time" ) func main() { start, _ := time.Parse(time.RFC822, "01 Jan 15 10:00 UTC") end, _ := time.Parse(time.RFC822, "01 Jan 16 10:00 UTC") in, _ := time.Parse(time.RFC822, "01 Jan 15 20:00 UTC") out, _ := time.Parse(time.RFC822, "01 Jan 17 10:00 UTC") if inTimeSpan(start, end, in) { fmt.Println(in, "is between", start, "and", end, ".") } if !inTimeSpan(start, end, out) { fmt.Println(out, "is not between", start, "and", end, ".") } } func inTimeSpan(start, end, check time.Time) bool { return check.After(start) && check.Before(end) }
The above is the detailed content of How to Compare Dates and Times in Go?. For more information, please follow other related articles on the PHP Chinese website!