解析特定時區的時間
使用 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中文網其他相關文章!