Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a date range in the format of YYYY-MM-DD from start to end in Golang?

Let’s say our inputs are start_date=2022-01-01 and end_date=2022-01-05. How I can get an input like below:

2022-01-01
2022-01-02
2022-01-03
2022-01-04

I’m able to parse start and end using time.Parse and get the days in between using .Sub and then iterating over the range and create string dates.
I was wondering if there is any method or better solution for date range creation in Go?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use:

const (
    layout = "2006-01-02"
)

func main() {
    startDate, _ := time.Parse(layout, "2022-01-01")
    endDate, _ := time.Parse(layout, "2022-01-05")

    for date := startDate; date.Before(endDate); date = date.AddDate(0, 0, 1) {
        fmt.Println(date.Format(layout))
    }
}

This will give you:

2022-01-01
2022-01-02
2022-01-03
2022-01-04

Full example

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading