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

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

问题描述

我有这个日期时间,或类似的日期。

  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-07-07 MST 2006 

请参阅以下工作代码:

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

输出(在去游乐场):

  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字符串转换为时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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