Home > Backend Development > Golang > 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
Release: 2024-02-12 18:00:07
forward
1172 people have browsed it

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
Copy after login
Copy after login

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))
    }
}
Copy after login

This will give you:

2022-01-01
2022-01-02
2022-01-03
2022-01-04
Copy after login
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template