Home  >  Article  >  Backend Development  >  How to create a date range in YYYY-MM-DD format from start to end in Golang?

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

WBOY
WBOYforward
2024-02-12 18:00:071125browse

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

Question content

Assume our input is start_date=2022-01-01 and end_date=2022-01-05. How do I get input like this:

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

I can use time.parse to parse the start and end and use .sub to get the number of days in between, then iterate over the range and create the string date. I was wondering if there is a way to create a date range in go or a better solution?

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

The above is the detailed content of How to create a date range in YYYY-MM-DD format from start to end in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete