I'm trying to get date and time like this 2014-06-22 22:00:22 GMT+2 What is the best way to do it?
I'm trying various variants. The closest was this
time.Now().Format("2006-01-02 15:04:05 GMT+1")
And I get good result, except the GMT - it's wrong. I'v triyed to change the template like this and got results:
GMT+0 => GMT+0
GMT+1 => GMT+4
But I live in GMT+3 and expect that number. What am I doing wrong?
Per the documentation the time
package supports hhmm
, hh:mm
, and hh
formats; single-digit h
offset is not directly supported:
Numeric time zone offsets format as follows:
-0700 ±hhmm
-07:00 ±hh:mm
-07 ±hh
Remember that the format string for time.Format
is telling it how to render the parts of Time. It does not change anything about the Time
, including its locale. If you want to render a time in a different time zone, use Time.In
to get the time in a different time zone:
timeInGMTPlus3 := time.Now().In(time.FixedZone("some zone", int((3 * time.Hour).Seconds()))
For example, for Moscow, GMT+03,
package main
import (
"fmt"
"time"
)
func main() {
// Your Local time zone
now := time.Now().Round(0)
fmt.Println(now.UTC())
fmt.Println(now)
t := now.Format("2006-01-02 15:04:05 GMT-07")
fmt.Println(t)
// For example, use Moscow time zone (GMT+03)
fmt.Println()
moscow, err := time.LoadLocation("Europe/Moscow")
if err != nil {
panic(err)
}
now = time.Now().In(moscow)
fmt.Println(now.UTC())
fmt.Println(now)
t = now.Format("2006-01-02 15:04:05 GMT-07")
fmt.Println(t)
}
Output:
2019-04-19 17:24:20.582630875 +0000 UTC
2019-04-19 13:24:20.582630875 -0400 EDT
2019-04-19 13:24:20 GMT-04
2019-04-19 17:24:20.582729015 +0000 UTC
2019-04-19 20:24:20.582729015 +0300 MSK
2019-04-19 20:24:20 GMT+03