登录
首页 >  Golang >  Go问答

硬编码int值与time.Date()返回值不一致的原因是什么?

来源:stackoverflow

时间:2024-02-08 11:18:24 413浏览 收藏

一分耕耘,一分收获!既然都打开这篇《硬编码int值与time.Date()返回值不一致的原因是什么?》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

我正在尝试从 api 中检索数据,其中我的请求必须具有开始和结束 unix 时间戳,但我的方法得到了非常奇怪的结果。

(我将在基于 go 演示的示例中使用日期,该演示始终将 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)
}

正确答案


您已反转 date() 的返回值。应该是这样的:

year, month, day := twoDaysAgo.Date()

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>