Here below is my code to get the last complete quarter:
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
", startDate.Format("2006-01-02"))
fmt.Printf("End date: %v
", endDate.Format("2006-01-02"))
}
<kbd>playground</kbd>
Is there a better way to get the correct start date?
For instance, the last startDate = startDate.AddDate(0, 0, 1)
statement has to be omitted if I want to get the last semester:
endDate := now.AddDate(0, 0, 0-now.Day())
startDate := endDate.AddDate(0, -6, 0) // startDate is correct: 2017-05-01
Why is there this difference?