GoLang解析time.Now()时不包含时区的方法是什么?

huangapple go评论92阅读模式
英文:

GoLang parsing time.Now() sans timezone?

问题

我在程序中有以下代码,目标是确保在特定时间范围内可以访问某个项目。但出现了一个问题,结果始终为false。我已经记录了开始时间、结束时间和当前时间。开始和结束日期通过JSON请求传入,没有时区信息。而time.Now()函数返回的是带有时区信息的时间。这可能是问题所在吗?我该如何解决?

func withinStartAndEnd(item Item) bool {
    fmt.Println("Start Date", item.Start_date, "\n")
    fmt.Println("End Date", item.End_date, "\n")
    fmt.Println("Now:", time.Now(), "\n")

    //BUG: For some reason event 0's are still not accessible within the timeframe. The fmt's above are to help look at it. time.Now() is printing MST.. maybe that's it?

    /*
    Start Date 2016-02-19 09:50:00 +0000 +0000
    End Date 2016-02-19 10:00:00 +0000 +0000
    Now: 2016-02-19 09:59:48.73003196 -0700 MST

    2016/02/19 09:59:48 Item not accessible (#148)
    */
    return item.Start_date.Before(time.Now()) && item.End_date.After(time.Now())
}
英文:

I have the following code in a program and the goal is to make sure an item is accessible within a timeframe. For some reason, this is coming in as false. I've logged the start, end, and now times.The start/end dates are coming in through a JSON request, with no timezone. The time.Now() is giving a timezone. Is that where I'm having my issue? How would I fix it?

func withinStartAndEnd(item Item) bool {
    fmt.Println("Start Date", item.Start_date, "\n")
    fmt.Println("End Date", item.End_date, "\n")
    fmt.Println("Now:", time.Now(), "\n")

    //BUG: For some reason event 0's are still not accessible within the timeframe. The fmt's above are to help look at it. time.Now() is printing MST.. maybe that's it?
    
    /*
    
    Start Date 2016-02-19 09:50:00 +0000 +0000
    End Date 2016-02-19 10:00:00 +0000 +0000
    Now: 2016-02-19 09:59:48.73003196 -0700 MST

    2016/02/19 09:59:48 Item not accessible (#148)

     */
    return item.Start_date.Before(time.Now()) && item.End_date.After(time.Now())
}

答案1

得分: 1

如果确实没有时区信息,那么可以使用协调世界时(Coordinated Universal Time,UTC)。

now := time.Now().UTC()

目标是将所有时间转换为UTC时间。也许,由于数据库时间实际上是MST(Mountain Standard Time):

// 数据库时区为Mountain Time
dbt, err := time.LoadLocation("America/Denver")
if err != nil {
    fmt.Println(err)
    return
}

now := time.Now().UTC()
start := item.Start_date.In(dbt).UTC()
end := item.End_date.In(dbt).UTC()
英文:

If there really is no time zone, then use UTC, the Coordinated Universal Time.

now := time.Now().UTC()

The goal is to get everything to UTC time. Perhaps, since DB time is actually MST,

// database time zone is Mountain Time
dbt, err := time.LoadLocation("America/Denver")
if err != nil {
	fmt.Println(err)
	return
}

now := time.Now().UTC()
start := item.Start_date.In(dbt).UTC()
end := item.End_date.In(dbt).UTC()

huangapple
  • 本文由 发表于 2016年2月20日 01:13:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/35510984.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定