解组日期格式不正确的日期

背景

我正在学习Go,并且正在尝试对日期时间进行JSON解组。

我有一个用C语言编写的程序生成的JSON,我正在输出我认为有效的ISO8601

/

RFC3339时区偏移量。我正在使用strftime以下格式字符串:

%Y-%m-%dT%H:%M:%S.%f%z

(请注意,本机%f不支持strftime,我有一个包装器将其替换为纳秒级)。

然后,将产生以下结果:

2016-08-08T21:35:14.052975+0200

但是在Go中取消编组此功能将无效:https :

//play.golang.org/p/vzOXbzAwdW

package main

import (

"fmt"

"time"

)

func main() {

t, err := time.Parse(time.RFC3339Nano, "2016-08-08T21:35:14.052975+0200")

if err != nil {

panic(err)

}

fmt.Println(t)

}

输出:

panic: parsing time "2016-08-08T21:35:14.052975+0200" as "2006-01-02T15:04:05.999999999Z07:00": cannot parse "+0200" as "Z07:00"

(工作示例:https :

//play.golang.org/p/5xcM0aHsSw)

这是因为RFC3339期望时区偏移量02:00采用a

格式:,但将其strftime输出为0200

因此,我需要在C程序中修复此问题,以输出正确的格式。

 %z     The +hhmm or -hhmm numeric timezone (that is, the hour and

minute offset from UTC). (SU)

但是,现在我有一堆格式不正确的JSON文件:

2016-08-08T21:35:14.052975+0200

而不是正确的(:在时区偏移中):

2016-08-08T21:35:14.052975+02:00

但我仍然希望能够在Go程序中正确取消编组。最好两个具有此区别的不同JSON文件应该以完全相同的方式进行解析。

关于封送回JSON,应使用正确的格式。

这就是我在我中定义它的方式struct

Time            time.Time `json:"time"`

所以问题是,执行此操作的“执行”方式是什么?

同样在我的代码示例中,我正在使用RFC3339Nano。我还要如何在结构的元数据中指定它?正如我现在所拥有的json:"time"那样,那会忽略纳秒吗?

回答:

您可以定义time支持两种格式的自己的字段类型:

type MyTime struct {

time.Time

}

func (self *MyTime) UnmarshalJSON(b []byte) (err error) {

s := string(b)

// Get rid of the quotes "" around the value.

// A second option would be to include them

// in the date format string instead, like so below:

// time.Parse(`"`+time.RFC3339Nano+`"`, s)

s = s[1:len(s)-1]

t, err := time.Parse(time.RFC3339Nano, s)

if err != nil {

t, err = time.Parse("2006-01-02T15:04:05.999999999Z0700", s)

}

self.Time = t

return

}

type Test struct {

Time MyTime `json:"time"`

}

[Try on Go Playground](https://play.golang.org/p/nYESNHgJI8)

在上面的示例中,我们采用预定义的格式time.RFC3339Nano,其定义如下:

RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"

并删除 :

"2006-01-02T15:04:05.999999999Z0700"

time.Parse此处使用的这种时间格式在此处进行了描述:https : //golang.org/pkg/time/#pkg-

constants

另请参阅https://golang.org/pkg/time/#Parse的文档time.Parse

PS 2006在时间格式字符串中使用年份的事实可能是因为Golang的第一版于该年发布。

以上是 解组日期格式不正确的日期 的全部内容, 来源链接: utcz.com/qa/402610.html

回到顶部