Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang, time.Parse ( "11:22 PM" ) something that I can do math with

Tags:

time

go

I am importing a lot of fields of the format:

09:02 AM
10:02 AM
12:30 PM
04:10 PM
04:50 PM
05:30 PM

I would like to convert the fields into something I can do arithmetic on. For example, do a count down to when the event Occurs. Thus, saving the field in microseconds... or even seconds. I have been trying to get the time.Parse to work... no joy.

fmt.Println(time.Parse("hh:mm", m.Feed.Entry[i].GsxA100Time.T))

returns...

0001-01-01 00:00:00 +0000 UTC parsing time "07:50 PM" as "hh:mm": cannot parse "07:50 PM" as "hh:mm"

any suggestions?

like image 459
IrishGringo Avatar asked Jul 05 '17 11:07

IrishGringo


1 Answers

The layout string for time.Parse does not handle the "hh:mm" format. In your case, the layout string would rather be "03:04 PM" as you can see in the documentation.

To get a time.Duration after parsing the string, you can substract your time with a reference time, in your case I would assume "12:00 AM".

Working example:

package main

import (
    "fmt"
    "time"
)

func main() {
    ref, _ := time.Parse("03:04 PM", "12:00 AM")
    t, err := time.Parse("03:04 PM", "11:22 PM")
    if err != nil {
        panic(err)
    }

    fmt.Println(t.Sub(ref).Seconds())
}

Output:

84120

Playground

like image 136
ANisus Avatar answered Sep 24 '22 19:09

ANisus