Golang equivalent of strtotime("this Sunday, 23:59:59")

I am writing a scraper that scrapes offers off websites and these offers have end dates. One such website has offers that expire every Sunday. I have gone through the golang time documentation but still dont get how that can be done the equivalence I found in PHP and is pretty simple.

$endDate = strtotime('this Sunday, 23:59:59');

Is there a golang way to do this?

1 answer

  • answered 2018-11-08 10:27 peterSO

    Write a function in Go using the Go standard library time package. For example,

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func endDate(t time.Time, wd time.Weekday) time.Time {
        next := int((wd - t.Weekday() + 7) % 7)
        y, m, d := t.Date()
        return time.Date(y, m, d+next+1, 0, 0, 0, -1, t.Location())
    }
    
    func main() {
        now := time.Now().Round(0)
        fmt.Println(now, now.Weekday())
    
        end := endDate(now, time.Sunday)
        fmt.Println(end, end.Weekday())
    }
    

    Playground: https://play.golang.org/p/T0oZGRO9NV8

    Output:

    2018-11-08 05:25:01.104445722 -0500 EST Thursday
    2018-11-11 23:59:59.999999999 -0500 EST Sunday