如何获得最后一个季度



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

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: %vn", startDate.Format("2006-01-02"))
fmt.Printf("End date: %vn", endDate.Format("2006-01-02"))
}

操场

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

例如,如果我想获得最后一个学期,就必须省略最后一个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

为什么会有这种区别?

包时间

import "time"

func日期

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

Date返回对应的时间

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:  %vn", now.Format("2006-01-02"))
fmt.Printf("Start date: %vn", start.Format("2006-01-02"))
fmt.Printf("End date:   %vn", end.Format("2006-01-02"))
fmt.Println("Semester:")
start, end = lastPeriod(now, semester)
fmt.Printf("Base date:  %vn", now.Format("2006-01-02"))
fmt.Printf("Start date: %vn", start.Format("2006-01-02"))
fmt.Printf("End date:   %vn", 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

最新更新