将UTC字符串转换为golang时间对象 [英] Convert UTC string to golang time object

查看:952
本文介绍了将UTC字符串转换为golang时间对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个日期时间,或者看起来像这样的东西。

  2014-11-17 23:02:03 + 0000 UTC 

我想将其转换为时间对象,我无法生成任何输出从 time.Parse 除了:

  0001-01-01 00 :00:00 +0000 UTC 

我尝试过这些布局:

  time.RFC3339 
0001-01-01 00:00:00 0000 UTC
2016-10-10
时间.UnixDate

还有几个 - 没有工作。



这是我如何调用 parse

  updatedAt,err:= time.Parse(time.UnixDate,updatedAtVar)

如何创建时间对象来自一个字符串?

解决方案

很可能你使用了错误的布局,并没有检查返回的错误。 / p>

格式必须是这个日期/时间您的输入时间是:

  Mon Jan 2 15:04:05 -0700 MST 2006 

查看此工作代码:

 布局:=2006-01-02 15:04:05 -0700 MST
t,err:= time.Parse(layout,2014-11-17 23:02:03 +0000 UTC)
fmt.Println(t,err)

输出(尝试在 Go Playground ):

  2014-11-17 23:02:03 +0000 UTC< nil> 

编辑:



在您的问题中,您在输入时间(作为区域偏移量的一部分)中包含一个 + ,但是与其他格式的时间有误。 >

Time.String( ) 使用以下格式字符串:

 2006-01-02 15: 04:05.999999999 -0700 MST

所以要么用这个来解析时间,要么使用 Time.Format() 来制作您的字符串表示,您可以在其中指定布局,因此您可以使用相同的布局解析时间字符串。



第二轮:



您将时间字符串包含在URL中。 + 符号是URL编码中的特殊字符:它表示空格。因此, + 转换为空格(因此它从您的时间字符串中消失)。使用正确的URL编码!查看 net / url 包,此示例


I have this datetime, or something that looks like it.

2014-11-17 23:02:03 +0000 UTC

I want to convert this to a time object and I've been unable to produce any output from time.Parse apart from:

0001-01-01 00:00:00 +0000 UTC

I've tried these layouts:

time.RFC3339
0001-01-01 00:00:00 0000 UTC
2016-10-10
time.UnixDate

And a few more - none have worked.

This is how I'm calling parse :

updatedAt, err := time.Parse(time.UnixDate, updatedAtVar)

How do I create a time object from a string?

解决方案

Most likely you used a wrong layout, and you didn't check the returned error.

The layout must be this date/time, in the format your input time is:

Mon Jan 2 15:04:05 -0700 MST 2006

See this working code:

layout := "2006-01-02 15:04:05 -0700 MST"
t, err := time.Parse(layout, "2014-11-17 23:02:03 +0000 UTC")
fmt.Println(t, err)

Output (try it on the Go Playground):

2014-11-17 23:02:03 +0000 UTC <nil>

EDIT:

In your question you included a + sign in your input time (as part of the zone offset), but you have error with times of other formats.

Time.String() uses the following format string:

"2006-01-02 15:04:05.999999999 -0700 MST"

So either use this to parse the times, or use Time.Format() to produce your string representations where you can specify the layout, so you can use the same layout to parse the time strings.

2nd round:

You're including your time strings in URLs. The + sign is a special character in URL encoding: it denotes the space. So the + gets converted to space (and so it vanishes from your time string). Use proper URL encoding! Check out the net/url package, and this example.

这篇关于将UTC字符串转换为golang时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆