简体   繁体   中英

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

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?

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

Did you read the documentation of time.Parse? In the very beginning it says:

The layout defines the format by showing how the reference time, defined to be Mon Jan 2 15:04:05 -0700 MST 2006 would be interpreted if it were the value

In the beginning of the package documentation there are more details about the layout string. Note that you can omit some of the fields (in your case days, years and timezeone) and those will then always get zero value.

So fmt.Println(time.Parse("3:04 PM", "07:50 PM")) should work.

If you'll check again the documentation about time's Parse method you'll find the fact that Go's approach of parsing the time is totally different then the one that you used to work with in other languages. To provide the Parse function the layout of the time that you want to parse you need to transform one specific date (which is Mon Jan 2 15:04:05 -0700 MST 2006 ) into the layout that you're providing. In your case that would be "03:04 PM".

The full code: fmt.Println(time.Parse("03:04 PM", m.Feed.Entry[i].GsxA100Time.T))

Just in case anyone is working with epoch times can use this,

func convert (in int64) string {
    u := time.Unix(in/1000, in%1000)
    ampm := "AM"
    if u.Hour()/12 ==1 { ampm = "PM" }
    th := u.Hour()%12
    hh := strconv.Itoa(th)
    if th < 10 { hh = "0" + hh }
    tm := u.Minute()
    mm := strconv.Itoa(tm)
    if tm < 10 { mm = "0" + mm }
    return hh + ":" + mm + " " + ampm
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM