Time zone issues for Time.parse and Time.format in Golang

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Time zone issues for Time.parse and Time.format in Golang

posted in 2017-12-03 | classified in coding

First, the problem description

windowsunder, time.Parse() the time zone and time.Format() the time zone are consistent.

However, in an environment where the linux time.Parse() default time zone is UTC , time.Format() the time zone defaults to local, and the two will cause an error if not handled properly.

1
2
3
4
5
6
7
8
9
10
11
12
13
Package   main
Import "Time"
import "FMT"
func main(){
T, err: = time. Parse ("2006-01-02 15:04:05", "2017-12-03 22:01:02")
if err! = Nil{
FMT. PRINTLN (ERR)
return
}
FMT. Println (t)
FMT. Println (time. Now ())
FMT. Println (time. Now (). Sub (t). Seconds ())
}

Output:

1
2
3
2017-12-03 22:01:02 +0000 UTC
2017-12-03 22:15:26.592204446 +0800 CST m=+0.003020091
-27935.407549533

It is obvious that the time zone between the two is different and that if you subtract the time, the results do not meet the expectations.

Second, the solution

Use time.ParseInLocation() instead of time.Parse() :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Package   main

Import "Time"
import "FMT"

func main(){
localtime, err: = time. Parseinlocation ("2006-01-02 15:04:05", "2017-12-03 22:01:02", time. Local)
if err! = Nil{
FMT. PRINTLN (ERR)
return
}
FMT. Println (localtime)
FMT. Println (time. Now ())
FMT. Println (time. Now (). Sub (localtime). Seconds ())
}

Results:

1
2
3
2017-12-03 22:01:02 +0800 CST
2017-12-03 22:18:26.288174547 +0800 CST m=+0.001532618
1044.288357362
Golang Redis Small Case (ii): REDIS Implementation Message Queuing Redis Learning notes: Subscribing and publishing
    • Article Directory
    • Site Overview

Ma Yi Ma Yi Ma Yi

It's a long way to mend

291 log classification Links
    • Wordpress
    • Gitbooks
  1. First, the problem description
  2. Second, the solution

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.