我正在嘗試從 API 中檢索資料,其中我的請求必須具有開始和結束 unix 時間戳,并且我的方法得到了非常奇怪的結果。
(我將在基于 Go Playground 的示例中使用日期,它總是將 time.Now().UTC() 報告為 2009-11-10 23:00:00)
我將安排它每天運行,我希望它始終檢索 2 天前的所有記錄,所以我需要發送 2009-11-08 00:00:00 的開始時間和 2009 年的結束時間-11-08 23:59:59。
以下是我的方法的摘要:
// Retrieve the time now in UTC
now := time.Now().UTC()
// Subtract two days from now
twoDaysAgo := now.AddDate(0, 0, -2)
// Extract the day, month, and year individually,
// which will be used to "rebuild" or "reset" our clock to 00:00:00
day, month, year := twoDaysAgo.Date()
// Build our start time using the extracted day, month, and year
startTime := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
列印 startTime 時,我希望得到 2009-11-08 00:00:00 但得到 0014-05-02 00:00:00
游樂場鏈接
package main
import (
"fmt"
"time"
)
func main() {
// we are trying to "reset the clock" on a specified date, 2 days in the past from today.
// this time.Time will be used as a "start" timestamp for a request we want to make.
// first, get the current time, which is hardcoded in Go Playground to be 2009-11-10 23:00:00,
// and prints the expected value
now := time.Now().UTC()
fmt.Println("Now:", now)
// subtract two days, which should be 2009-11-08 23:00:00 and prints the expected value
twoDaysAgo := now.AddDate(0, 0, -2)
fmt.Println("Two days ago:", twoDaysAgo)
// extract the day, month, and year from twoDaysAgo, which should be 2009 November 8
// this prints the expected values so we can confirm that day, month, and year each contain what we need
day, month, year := twoDaysAgo.Date()
fmt.Println("Extracted day, month, and year:", day, month, year)
// create a new time.Time using time.Date() so we can "reset" the clock to 00:00:00
// we use day, month, and year extracted earlier as parameters to achieve this.
// this prints a wildly inaccurate date of 0014-05-02 00:00:00 for a reason I don't understand.
dateFromDateExtraction := time.Date(year, month, day, 0, 0, 0, 0, time.UTC)
fmt.Println("This date is weird: ", dateFromDateExtraction)
// if instead we hardcode the parameters for time.Date(),
// the result is what you expect and this prints 2009-11-08 00:00:00
dateHardcoded := time.Date(2009, time.November, 8, 0, 0, 0, 0, time.UTC)
fmt.Println("This date appears as expected: ", dateHardcoded)
}
uj5u.com熱心網友回復:
您已將回傳值從Date(). 應該是這樣的:
year, month, day := twoDaysAgo.Date()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/527057.html
標籤:日期约会时间去时间
