gpt4 book ai didi

go - 如何获得最后一个季度

转载 作者:IT王子 更新时间:2023-10-29 01:38:26 26 4
gpt4 key购买 nike

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

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

为什么会有这种差异?

最佳答案

Package time

import "time"

func Date

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

Date returns the Time corresponding to

yyyy-mm-dd hh:mm:ss + nsec nanoseconds

in the appropriate zone for that time in the given location.

The month, day, hour, min, sec, and nsec values may be outside their usual ranges and will be normalized during the conversion. For example, October 32 converts to November 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"))
}

Playground :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

关于go - 如何获得最后一个季度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47329733/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com