What is the method to use Go language to determine whether the time is yesterday?

PHPz
Release: 2024-03-23 22:18:04
Original
600 people have browsed it

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("输入的时间不是昨天")
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template