5

I'm reading a JSON file that contains Unix Epoch dates, but they are strings in the JSON. In Go, can I convert a string in the form "1490846400" into a Go time.Time?

Tigger
  • 109
  • 1
  • 7
  • 3
    Possible duplicate of [How to parse unix timestamp in golang](http://stackoverflow.com/questions/24987131/how-to-parse-unix-timestamp-in-golang) – Laurence Apr 15 '17 at 21:11

2 Answers2

13

There is no such function in time package, but it's easy to write:

func stringToTime(s string) (time.Time, error) {
    sec, err := strconv.ParseInt(s, 10, 64)
    if err != nil {
        return time.Time{}, err
    }
    return time.Unix(sec, 0), nil
}

Playground: https://play.golang.org/p/2h0Vd7plgk.

Ainar-G
  • 34,563
  • 13
  • 93
  • 119
7

There's nothing wrong, or incorrect about the answer provided by @Ainar-G, but likely a better way to do this is with a custom JSON unmarshaler:

type EpochTime time.Time

func (et *EpochTime) UnmarshalJSON(data []byte) error {
    t := strings.Trim(string(data), `"`) // Remove quote marks from around the JSON string
    sec, err := strconv.ParseInt(t, 10, 64)
    if err != nil {
        return err
    }
    epochTime := time.Unix(sec,0)
    *et = EpochTime(epochTime)
    return nil
}

Then in your struct, replace time.Time with EpochTime:

type SomeDocument struct {
    Timestamp EpochTime `json:"time"`
    // other fields
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189