Home > Back-end >  How to convert millisecond (uint64) into Time Format RFC3999 with millisecond (string) in GO
How to convert millisecond (uint64) into Time Format RFC3999 with millisecond (string) in GO

Time:02-19

How do i convert millisecond (uint64) into Time Format RFC3999 with millisecond (string) in GO?

For example:

var milleSecond int64
milleSecond = 1645286399999 //My Local Time : Sat Feb 19 2022 23:59:59

var loc = time.FixedZone("UTC-4", -4*3600)

string1 := time.UnixMilli(end).In(loc).Format(time.RFC3339) 

Actual Result: 2022-02-19T11:59:59-04:00

Expected Result(should be): 2022-02-19T11:59:59.999-04:00

CodePudding user response:

You are asking for an RFC3339 formatted string, with seconds reported to the nearest millisecond. There's no format string in the time package for this (only with whole seconds and nanosecond accuracy), but you can make your own.

Here's the string for seconds to the nearest nanosecond, copied from the standard library:

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

You can make a millisecond version of this easily enough by removing the .999999999 (report time to the nearest nanosecond, removing trailing zeros) to .000 (report time to the nearest millisecond, don't remove trailing zeros). This format is documented under time.Layout in the package docs https://pkg.go.dev/time#pkg-constants:

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

Code (playground link):

package main

import (
    "fmt"
    "time"
)

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

func main() {
    ms := int64(1645286399999) //My Local Time : Sat Feb 19 2022 23:59:59
    var loc = time.FixedZone("UTC-4", -4*3600)
    fmt.Println(time.UnixMilli(ms).In(loc).Format(RFC3339Milli))
}

Output:

2022-02-19T11:59:59.999-04:00

CodePudding user response:

I found a way which is using the format RFC3339nano

string1 := time.UnixMilli(end).In(loc).Format(time.RFC3339nano)

Have any other way??

  • Related