I've got a t time.Time
which I'm converting to an specific timezone and from which I need to extract both date and time (separately) as strings as follows:
Data should look like: 2006-09-23
Time should look like: 05:06:23
I'm doing the following:
t
to the needed timezone:var err error
loc, err := time.LoadLocation("America/Los_Angeles")
if err != nil {
return err
} else {
t = t.In(loc)
}
format := "2006-01-02 15:03:04"
timestamp := t.Format(format)
timestampSlice := strings.Fields(timestamp)
fmt.Println(timestampSlice[0])
fmt.Println(timestampSlice[1])
But I'm getting unexpected results for time (date works fine):
When passing
time.Date(2021, time.Month(2), 21, 1, 10, 30, 0, time.UTC)
I'd expect 2021-02-20
and 17:10:30
but I'm getting: 17:05:10
for the time
When passing
time.Date(2022, time.Month(8), 26, 22, 7, 30, 0, time.FixedZone("Asia/Shanghai", 0)),
I'd expect 2022-08-26
and 06:07:30
but I'm getting: 15:03:07
what am I doing wrong? does the values passed in the format have any effect in the parsing? I thought the format was only to signal the way the result should look
From the docs :
// Jan 2 15:04:05 2006 MST
// 1 2 3 4 5 6 -7
So the format 2006-01-02 15:03:04
would be parsed as years-months-days hours-hours-minutes
. Note that 15
refers to the hours (00-23), that 03
refers to the hours (1-12), and 04
refers to the minutes.
So the correct format would be
format := "2006-01-02 15:04:05"
You can learn more about formatting time here: https://pkg.go.dev/time#example-Time.Format
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.