Skip to content

Instantly share code, notes, and snippets.

@florentchauveau
Created August 30, 2018 13:22
Show Gist options
  • Select an option

  • Save florentchauveau/0ab3459d349b30bc78c6e9409e44e88a to your computer and use it in GitHub Desktop.

Select an option

Save florentchauveau/0ab3459d349b30bc78c6e9409e44e88a to your computer and use it in GitHub Desktop.

Revisions

  1. florentchauveau created this gist Aug 30, 2018.
    38 changes: 38 additions & 0 deletions epoch_to_time.go
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,38 @@
    // ConvertTS converts a UNIX timestamp string (with sub second precision) "epoch" into a time.Time
    // (c) Florent CHAUVEAU <[email protected]>

    func ConvertTS(ts string) time.Time {
    value := strings.SplitN(ts, ".", 2)

    var sec int64
    var nsec int64

    if len(value) == 0 {
    return time.Time{}
    }

    if len(value) == 1 {
    sec, _ = strconv.ParseInt(value[0], 10, 64)
    } else if len(value) == 2 {
    sec, _ = strconv.ParseInt(value[0], 10, 64)
    nsec, _ = strconv.ParseInt(value[1], 10, 64)

    // "1527589078.5418" -> 541800000 nsec
    // "1527589067.8157027" -> 815702700 nsec
    // "1527589073.0891006" -> 89100600 nsec
    // " .000000001" (1 nsec)
    // " .000000042" (42 nsec)
    // " .000000423" (423 nsec)

    x := 9 - len(value[1])

    if x > 0 {
    // "5418" becomes 541800000
    // "0891006" becomes 89100600
    // "000000001" stays 000000001
    nsec = nsec * int64(math.Pow10(x))
    }
    }

    return time.Unix(sec, nsec).UTC()
    }