Home > front end >  check if timestamp between 2 dates
check if timestamp between 2 dates

Time:12-22

I have dates stored as timestamps in mongo, for example, 1564444800000000000. I want to check if a timestamp is between 2 dates - July 1, 2021 and July, 2021. I converted these 2 dates to timestamps using https://www.epochconverter.com/. I first fetched all records and while looping through the records, I did a check like so

cDate := 1564444800000000000
if  cDate > 1625167488000 &&  cDate <  1627759488000 {
        log.Fatal("found one!")
}

But this not seem to work as I get no matches. Is there a better way of doing this?

CodePudding user response:

I mean just looking at the numbers:

cDate := 1564444800000000000
               1625167488000
               1627759488000

I don't see how one with six more digits than the one's it's supposed to be between would ever be between them. And even if we divided CDate by 1000000 it would be

cDate := 1564444800000
         1625167488000
         1627759488000

and it's still less than both of those, so it still wouldn't be between them. But that being said, you most likely do just need to divide cDate by 1000000 and your example is just not a good one (since 1564444800000 is July 29 2019)

CodePudding user response:

I suggest to transform in a date then check with the before and after API, as example:

package main

import (
    "fmt"
    "time"
)

func main() {
    cDate := int64(1564444800000000000)
    firstJuly := time.Date(2019, 7, 1, 0, 0, 0, 0, time.UTC)
    thrirtyOneJuly := time.Date(2019, 7, 31, 0, 0, 0, 0, time.UTC)

    date := time.Unix(0, cDate)
    // fmt.Println(date) //will print 2019-07-30 00:00:00  0000 UTC
    fmt.Println("Is July?", date.After(firstJuly) && date.Before(thrirtyOneJuly))
}

will print

Is July? true

See on playground

  •  Tags:  
  • go
  • Related