如何获得最后一个季度

时间:2017-11-16 12:31:15

标签: go

以下是我获得最后一个完整季度的代码:

package main

import (
    "fmt"
    "time"
)

func main() {
    layout := "2006-01-02T15:04:05.000Z"
    str := "2017-11-30T12:00:00.000Z"
    now, _ := time.Parse(layout, str)

    endDate := now.AddDate(0, 0, 0-now.Day())
    startDate := endDate.AddDate(0, -3, 0) // startDate is wrong: 2017-07-31
    // the following statement is needed to fix startDate
    if endDate.Month()-startDate.Month() == 3 {
        startDate = startDate.AddDate(0, 0, 1) // now startDate is correct: 2017-08-01
    }

    fmt.Printf("Start date: %v\n", startDate.Format("2006-01-02"))
    fmt.Printf("End date: %v\n", endDate.Format("2006-01-02"))
}

playground

有没有更好的方法来获得正确的开始日期?

例如,如果我想获得最后一个学期,则必须省略最后一个startDate = startDate.AddDate(0, 0, 1)语句:

endDate := now.AddDate(0, 0, 0-now.Day())
startDate := endDate.AddDate(0, -6, 0) // startDate is correct: 2017-05-01

为什么会出现这种差异?

1 个答案:

答案 0 :(得分:3)

  

Package time

import "time"
     

func Date

func Date(year int, month Month, day, hour, min, sec, nsec int, loc *Location) Time
     

日期返回与

对应的时间
yyyy-mm-dd hh:mm:ss + nsec nanoseconds
     

在指定地点的适当区域。

     

月,日,小时,分钟,秒和nsec值可能超出其范围   通常的范围,并将在转换过程中标准化。对于   例如,10月32日转换为11月1日。

例如,使用规范化来获取最后一个完整的句点(例如,季度或学期):

package main

import (
    "fmt"
    "time"
)

func lastPeriod(t time.Time, period time.Month) (start, end time.Time) {
    y, m, _ := t.Date()
    loc := t.Location()
    start = time.Date(y, m-period, 1, 0, 0, 0, 0, loc)
    end = time.Date(y, m, 1, 0, 0, 0, -1, loc)
    return start, end
}

func main() {
    layout := "2006-01-02T15:04:05.000Z"
    str := "2017-11-30T12:00:00.000Z"
    now, err := time.Parse(layout, str)
    if err != nil {
        fmt.Println(err)
        return
    }
    const (
        quarter  = 3
        semester = 6
    )
    fmt.Println("Quarter:")
    start, end := lastPeriod(now, quarter)
    fmt.Printf("Base date:  %v\n", now.Format("2006-01-02"))
    fmt.Printf("Start date: %v\n", start.Format("2006-01-02"))
    fmt.Printf("End date:   %v\n", end.Format("2006-01-02"))
    fmt.Println("Semester:")
    start, end = lastPeriod(now, semester)
    fmt.Printf("Base date:  %v\n", now.Format("2006-01-02"))
    fmt.Printf("Start date: %v\n", start.Format("2006-01-02"))
    fmt.Printf("End date:   %v\n", end.Format("2006-01-02"))
}

游乐场:https://play.golang.org/p/0t4exjVgr-

输出:

Quarter:
Base date:  2017-11-30
Start date: 2017-08-01
End date:   2017-10-31
Semester:
Base date:  2017-11-30
Start date: 2017-05-01
End date:   2017-10-31