Comparing two dates without regard to time

I have two dates like this, I would like to compare only dates, ignoring the time. I currently have this:

package main

import (
    "time"
    //"fmt"
)

func main() {
    a, _ := time.Parse(time.RFC3339, "2017-02-01T12:00:00+00:00")
    b, _ := time.Parse(time.RFC3339, "2017-02-11T14:30:00+00:00")

    x := b.Sub(a)

    println(int(x.Hours()))
}

      

What prints 242

. This is correct, but what I really want to do is compare dates like this:

    a, _ := time.Parse(time.RFC3339, "2017-02-01T00:00:00+00:00")
    b, _ := time.Parse(time.RFC3339, "2017-02-11T00:00:00+00:00")

      

Note: minutes / hours / seconds are set to zero - now the difference will be 240 hours.

I couldn't figure out how to do this, is there a function time.SetTime(0, 0, 0)

in Go that I missed, or a canonical way to reset the time for a date?

+3


source to share


2 answers


You can take the Truncate

time to make them round to a multiple of the day.

In your example:



oneDay := 24 * time.Hour
a = a.Truncate(oneDay)
b = b.Truncate(oneDay)

      

Find the game board with adapted code here: https://play.golang.org/p/yWIYt3UkiT

+3


source


If you are using time.Time you have to be careful enough because there may be edge cases at the beginning and end of daylight saving time.

Shameless plugin: I wrote a Date package (in fact, it was sourced from someone even earlier work) to handle dates without causing DST issues.

https://github.com/rickb777/date

You can do for example



a := date.New(2017, 2, 1)
b := date.New(2017, 2, 11)
daysDifference := b.Sub(a)
fmt.Println(daysDifference)

      


There are other subpackages to handle date ranges, time periods, ISO8601 periods, and time times.

0


source







All Articles