Home > Article > Backend Development > What is the method to use Go language to determine whether the time is yesterday?
How to use Go language to determine whether the time is yesterday
In Go language, we can determine a time by getting the current time and then subtracting 24 hours. Whether the time is yesterday. The following is a specific code example:
package main import ( "fmt" "time" ) func isYesterday(t time.Time) bool { yesterday := time.Now().Add(-24 * time.Hour) year, month, day := yesterday.Date() yesterdayStart := time.Date(year, month, day, 0, 0, 0, 0, yesterday.Location()) yesterdayEnd := time.Date(year, month, day, 23, 59, 59, 999999999, yesterday.Location()) return t.After(yesterdayStart) && t.Before(yesterdayEnd) } func main() { t := time.Date(2022, 1, 20, 12, 0, 0, 0, time.UTC) if isYesterday(t) { fmt.Println("输入的时间是昨天") } else { fmt.Println("输入的时间不是昨天") } }
In the above code, we first define a function named isYesterday
, which accepts a time.Time
Type parameter and returns a Boolean value indicating whether the time is yesterday. Inside the function, we first get the current time and subtract 24 hours, then create yesterday's start time and end time. Finally, we determine whether the entered time is yesterday by comparing whether it is within yesterday's time range.
In the main
function, we create a time object t
and call the isYesterday
function to determine whether the time is yesterday. Based on the returned Boolean value, we output the corresponding result.
Through the above code examples, we can use Go language to determine whether a time is yesterday, so as to perform more flexible time processing and logical judgment.
The above is the detailed content of What is the method to use Go language to determine whether the time is yesterday?. For more information, please follow other related articles on the PHP Chinese website!