Home > Backend Development > Golang > How to Compare Dates and Times in Go?

How to Compare Dates and Times in Go?

DDD
Release: 2024-12-20 19:01:09
Original
787 people have browsed it

How to Compare Dates and Times in Go?

Comparing Dates and Times in Go

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)
}
Copy after login

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!

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