什么是使用golang AddDate计算日期的正确方法

Today is 2018-11-1, I use AddDate to calculate 7 days: startTime := time.Now().AddDate(0, 0, -7).Unix(), but 2018-10-25 still exist. What is the correct way to calculate date use AddDate method?

Package time

import "time"

func (Time) AddDate

func (t Time) AddDate(years int, months int, days int) Time

AddDate returns the time corresponding to adding the given number of years, months, and days to t. For example, AddDate(-1, 2, 3) applied to January 1, 2011 returns March 4, 2010.

AddDate normalizes its result in the same way that Date does, so, for example, adding one month to October 31 yields December 1, the normalized form for November 31.


startTime := time.Now().AddDate(0, 0, -7) calculates the time minus 7 (-7) days or 7 days ago.

For example,

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println(time.Now().Round(0))
    startTime := time.Now().AddDate(0, 0, -7)
    fmt.Println(startTime)
}

Output (right now in the US it is 2018-10-31 21:30:40 EDT):

2018-10-31 21:30:40.977401051 -0400 EDT
2018-10-24 21:30:40.977510166 -0400 EDT

In your time zone, it is currently 2018-11-01, so minus 7 (-7) days or 7 days ago is 2018-10-25.


Note: There are two ways to count days. For age, today you are one day older than yesterday. For pay, working yesterday and today is two days pay.