」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何使用 time.ParseInLocation() 解析特定時區的時間字串?

如何使用 time.ParseInLocation() 解析特定時區的時間字串?

發佈於2024-11-22
瀏覽:184

How to Parse Time Strings in Specific Time Zones with `time.ParseInLocation()`?

使用time.ParseInLocation 進行自訂時區解析

使用time.ParseTime() 函數解析時間時,產生的時間結構將是預設採用UTC,這可能並不總是理想的行為。為了解決這個問題,您可以利用 time.ParseInLocation() 函數,它允許您在解析期間指定特定的時區。

例如,如果您想要取得除以下時區以外的時間結構UTC,您可以使用 time.Local 作為 Location 參數。這可以確保產生的時間物件將反映您本地時區中的指定時間戳記。

下面有一個範例來說明:

package main

import (
    "fmt"
    "time"
)

func main() {
    // Parse time with a specific time zone.
    // 2012-07-09 05:02:00  0000 CEST
    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)

    // Parse time without a specific time zone, will use local time zone.
    // 2012-07-09 05:02:00 -0700 PDT
    const formWithoutZone = "Jan 2, 2006 at 3:04pm"
    t, _ = time.ParseInLocation(formWithoutZone, "Jul 9, 2012 at 5:02am", time.Local)
    fmt.Println(t)
}

透過使用 time.ParseInLocation(),您可以輕鬆解析時間字串並取得任何所需時區的時間結構,從而更靈活地控制時間表示。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3