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
?
CodePudding user response:
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