How to create a slice of dates between a start and end date in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "time"
)

// GenerateDates returns all dates from start to end (inclusive).
func GenerateDates(start, end time.Time) []time.Time {
    var dates []time.Time

    // Normalize times to midnight to avoid DST issues
    start = time.Date(start.Year(), start.Month(), start.Day(), 0, 0, 0, 0, start.Location())
    end = time.Date(end.Year(), end.Month(), end.Day(), 0, 0, 0, 0, end.Location())

    if start.After(end) {
        return dates
    }

    for d := start; !d.After(end); d = d.AddDate(0, 0, 1) {
        dates = append(dates, d)
    }

    return dates
}

func main() {
    start := time.Date(2026, 1, 3, 0, 0, 0, 0, time.UTC)
    end   := time.Date(2026, 1, 12, 0, 0, 0, 0, time.UTC)

    dates := GenerateDates(start, end)

    fmt.Printf("Generated %d dates:\n", len(dates))
    for _, d := range dates {
        fmt.Println(d.Format("2006-01-02"))
    }
}


/*
run:

Generated 10 dates:
2026-01-03
2026-01-04
2026-01-05
2026-01-06
2026-01-07
2026-01-08
2026-01-09
2026-01-10
2026-01-11
2026-01-12

*/

 



answered Jan 31 by avibootz
...