代码之家  ›  专栏  ›  技术社区  ›  rellocs wood

如何在go中优雅地迭代日期范围

go
  •  -2
  • rellocs wood  · 技术社区  · 6 年前

    我需要迭代任何指定的日期范围,比如2017-12-21到2018-01-05。在go中最好的实现方法是什么?

    output:
    20171221
    20171222
    20171223
    ...
    20180104
    20180105
    
    1 回复  |  直到 6 年前
        1
  •  6
  •   peterSO    6 年前

    The Go Programming Language Specification

    Function literals

    函数文字表示匿名函数。

    FunctionLit = "func" Signature FunctionBody .
    
    func(a, b int, z float64) bool { return a*b < int(z) }
    

    函数文字可以直接分配给变量或直接调用。

    f := func(x, y int) int { return x + y }
    func(ch chan int) { ch <- ACK }(replyChan)
    

    函数文本是闭包:它们可以引用 周围的功能。然后这些变量在 环绕函数和函数文字,它们作为 只要他们可以接近。


    在go中,将复杂性封装在函数中。使用函数文字作为闭包。

    例如,

    package main
    
    import (
        "fmt"
        "time"
    )
    
    // rangeDate returns a date range function over start date to end date inclusive.
    // After the end of the range, the range function returns a zero date,
    // date.IsZero() is true.
    func rangeDate(start, end time.Time) func() time.Time {
        y, m, d := start.Date()
        start = time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
        y, m, d = end.Date()
        end = time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
    
        return func() time.Time {
            if start.After(end) {
                return time.Time{}
            }
            date := start
            start = start.AddDate(0, 0, 1)
            return date
        }
    }
    
    func main() {
        start := time.Now()
        end := start.AddDate(0, 0, 6)
        fmt.Println(start.Format("2006-01-02"), "-", end.Format("2006-01-02"))
    
        for rd := rangeDate(start, end); ; {
            date := rd()
            if date.IsZero() {
                break
            }
            fmt.Println(date.Format("2006-01-02"))
        }
    }
    

    游乐场: https://play.golang.org/p/wmfQC9fEs1S

    输出:

    2018-06-22 - 2018-06-28
    2018-06-22
    2018-06-23
    2018-06-24
    2018-06-25
    2018-06-26
    2018-06-27
    2018-06-28