How to convert datetime string to RFC3339

Hi,

I am new to golang and wondering if anyone can help with this query.

How do I convert a date string in the format “2005-06-13 04:40:51” to RFC3339 date string UTC, e.g. “2005-06-13T04:40:51.000Z”?

Tried:

    createdOn, err := time.Parse("2006-01-02 03:04:05", p.CreatedOn)
    fmt.Println(err.Error())
	
    result := createdOn.Format(time.RFC3339)

which gives error:

CreatedOn:  1986-12-03 22:01:35

parsing time "1986-12-03 22:01:35": hour out of range

As suggested in an answer below, I changed the hour to 24hr format:

createdOn, _ := time.Parse("2006-01-02 15:04:05", p.CreatedOn)
self.CreatedOn = createdOn.Format(time.RFC3339)

For example, this will give a date string in the format:

1970-02-13T10:31:13Z

How do I get it to be in the format 1970-02-13T10:31:13.000Z ?

write 15 instead of 03 for the hour.

Many many thanks!

Yes that did the trick!

createdOn, _ := time.Parse("2006-01-02 15:04:05", p.CreatedOn)
self.CreatedOn = createdOn.Format(time.RFC3339)

For example, this will give a date string in the format:

1970-02-13T10:31:13Z

How do I get it to be in the format 1970-02-13T10:31:13.000Z ?

Looks like there’s time.RFC3339 which only includes seconds and time.RFC3339Nano which includes nanoseconds, but I don’t see anything in between. You may have to devine your own format:

RFC3339Milli = "2006-01-02T15:04:05.000Z07:00"

Many thanks, will investigate further.

You can try go-carbon, it supports all RFC output formats
eg:

// To string of RFC822 format
carbon.Parse(“2020-08-05 13:14:15”).ToRfc822String() // 05 Aug 20 13:14 CST
// To string of RFC822Z format
carbon.Parse(“2020-08-05 13:14:15”).ToRfc822zString() // 05 Aug 20 13:14 +0800
// To string of RFC850 format
carbon.Parse(“2020-08-05 13:14:15”).ToRfc850String() // Wednesday, 05-Aug-20 13:14:15 CST
// To string of RFC1036 format
carbon.Parse(“2020-08-05 13:14:15”).ToRfc1036String() // Wed, 05 Aug 20 13:14:15 +0800
// To string of RFC1123 format
carbon.Parse(“2020-08-05 13:14:15”).ToRfc1123String() // Wed, 05 Aug 2020 13:14:15 CST
// To string of RFC2822 format
carbon.Parse(“2020-08-05 13:14:15”).ToRfc2822String() // Wed, 05 Aug 2020 13:14:15 +0800
// To string of RFC3339 format
carbon.Parse(“2020-08-05 13:14:15”).ToRfc3339String() // 2020-08-05T13:14:15+08:00
// To string of RFC7231 format
carbon.Parse(“2020-08-05 13:14:15”).ToRfc7231String() // Wed, 05 Aug 2020 05:14:15 GMT

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.