Adrian
Adrian

Reputation: 20068

How to convert a string time with milliseconds (hh:mm:ss.xxx) to time.Time?

Basically I have times like this one as a string:

15:56:36.113

I want to convert it to time.Time.

From what I am reading I cannot use milliseconds when using time.Parse().

Is there another way to convert my string to time.Time ?

Upvotes: 3

Views: 5143

Answers (2)

peterSO
peterSO

Reputation: 166596

Package time

Format Reference Time

A decimal point followed by one or more zeros represents a fractional second, printed to the given number of decimal places. A decimal point followed by one or more nines represents a fractional second, printed to the given number of decimal places, with trailing zeros removed. When parsing (only), the input may contain a fractional second field immediately after the seconds field, even if the layout does not signify its presence. In that case a decimal point followed by a maximal series of digits is parsed as a fractional second.

For example,

package main

import (
    "fmt"
    "time"
)

func main() {
    t, err := time.Parse("15:04:05", "15:56:36.113")
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(t)

    fmt.Println(t.Format("15:04:05.000"))

    h, m, s := t.Clock()
    ms := t.Nanosecond() / int(time.Millisecond)
    fmt.Printf("%02d:%02d:%02d.%03d\n", h, m, s, ms)
}

Output:

0000-01-01 15:56:36.113 +0000 UTC
15:56:36.113
15:56:36.113

Note: The zero value of type Time is 0000-01-01 00:00:00.000000000 UTC.

Upvotes: 2

Alex Efimov
Alex Efimov

Reputation: 3703

package main

import (
    "fmt"
    "time"
)

func main() {
    s := "15:56:36.113"
    t,_ := time.Parse("15:04:05.000", s)

    fmt.Print(t)
}

Output:

0000-01-01 15:56:36.113 +0000 UTC

You can play with it more here: https://play.golang.org/p/3A3e8zHQ8r

Upvotes: 1

Related Questions