首页 > 后端开发 > Golang > 正文

如何在Go中解析特定时区的时间?

Mary-Kate Olsen
发布: 2024-10-24 17:15:02
原创
617 人浏览过

How to Parse Time in a Specific Timezone in Go?

解析特定时区的时间

使用 time.ParseTime() 解析时间字符串时,生成的时间结构通常采用 UTC 格式。但是,如果您需要不同的时区,可以通过以下方法实现:

解决方案:

当时间到达时,利用 time.ParseInLocation 解析给定位置的时间区域没有明确指定。 time.Local 代表您当地的时区,因此将其作为 Location 传递将解决该问题:

<code class="go">import (
    "fmt"
    "time"
)

func main() {
    // Honor given time zone
    const formWithZone = "Jan 2, 2006 at 3:04pm (MST)"
    t, _ := time.ParseInLocation(formWithZone, "Jul 9, 2012 at 5:02am (CEST)", time.Local)
    fmt.Println(t)  // Output: 2012-07-09 05:02:00 +0000 CEST

    // Default to local time zone
    const formWithoutZone = "Jan 2, 2006 at 3:04pm"
    t, _ = time.ParseInLocation(formWithoutZone, "Jul 9, 2012 at 5:02am", time.Local)
    fmt.Println(t)  // Output: 2012-07-09 05:02:00 -0700 PDT
}</code>
登录后复制

在第一个示例中,使用指定时区 (CEST) 解析时间并返回一个时间结构那个时区。在第二个示例中,由于未提供时区,因此以本地时区 (PDT) 解析时间。

以上是如何在Go中解析特定时区的时间?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!