golang - 枚举两个时间内的所有天(包含起始时间和终止时间)

go-bot

2018-05-23T08:26:34Z||2018-05-23T08:26:34Z

比如,枚举2020-02-25到2020-03-04内的所有天:

package main

import (
    "fmt"
    "time"
)

type Day struct {
    Start time.Time
    End   time.Time
}

func EnumerateDaysFromRange(start, end time.Time) []Day {
    days := make([]Day, 0)
    for day := start; !day.After(end); day = day.AddDate(0, 0, 1) {
        // Get end of the day
        dayEnd := day.AddDate(0, 0, 1).Add(-time.Nanosecond)

        day := Day{Start: day, End: dayEnd}
        days = append(days, day)
    }
    return days
}

func main() {
    s, err := time.Parse("2006-1-2", "2020-02-25")
    if err != nil {
        panic(err)
    }
    e, err := time.Parse("2006-1-2", "2020-03-04")
    if err != nil {
        panic(err)
    }

    days := EnumerateDaysFromRange(s, e)
    for _, d := range days {
        fmt.Printf("%v - %v\n", d.Start, d.End)
    }
}

输出:

2020-02-25 00:00:00 +0000 UTC - 2020-02-25 23:59:59.999999999 +0000 UTC
2020-02-26 00:00:00 +0000 UTC - 2020-02-26 23:59:59.999999999 +0000 UTC
2020-02-27 00:00:00 +0000 UTC - 2020-02-27 23:59:59.999999999 +0000 UTC
2020-02-28 00:00:00 +0000 UTC - 2020-02-28 23:59:59.999999999 +0000 UTC
2020-02-29 00:00:00 +0000 UTC - 2020-02-29 23:59:59.999999999 +0000 UTC
2020-03-01 00:00:00 +0000 UTC - 2020-03-01 23:59:59.999999999 +0000 UTC
2020-03-02 00:00:00 +0000 UTC - 2020-03-02 23:59:59.999999999 +0000 UTC
2020-03-03 00:00:00 +0000 UTC - 2020-03-03 23:59:59.999999999 +0000 UTC
2020-03-04 00:00:00 +0000 UTC - 2020-03-04 23:59:59.999999999 +0000 UTC