简体   繁体   中英

How can I parse date and time directly with timezone

I have these codes:

package main

import (
    "fmt"
    "time"
)

func main() {
    tzJakarta, _ := time.LoadLocation("Asia/Jakarta")
    stringTime := fmt.Sprintf("05-05-2019 05:11 %s", tzJakarta) 
    parsedTime, _ := time.Parse("02-01-2006 15:04 MST", stringTime)

    fmt.Println(tzJakarta)
    fmt.Println(stringTime)
    fmt.Println(parsedTime)
}

The output is:

Asia/Jakarta
05-05-2019 05:11 Asia/Jakarta
0001-01-01 00:00:00 +0000 UTC

What I expect is this:

Asia/Jakarta
05-05-2019 05:11 Asia/Jakarta
0001-01-01 00:00:00 +0700 UTC

How can I achieve this? Is this possible at all with Go?

You will never have 0001-01-01 00:00:00 +0700 UTC because you're ignoring errors, 0001-01-01 00:00:00 +0000 UTC is a zero value. Last statement returns an error about parsing, here is a right version.

package main

import (
    "fmt"
    "time"
)

func main() {
    loc, _ := time.LoadLocation("Asia/Jakarta")

    // Note: without explicit zone, returns time in given location.
    const shortForm = "02-01-2006 15:04"
    t, _ := time.ParseInLocation(shortForm, "05-05-2019 05:11", loc)
    fmt.Println(t)

}

Output:

2019-05-05 05:11:00 +0700 WIB 

(WIB – Western Indonesian Time)

Platground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM