当前位置: 动力学知识库 > 问答 > 编程问答 >

time - Go, get hours difference between two dates

问题描述:

I'm working for first time on Go, in this case i have a string on UTC format, I would like to know, how can I get the difference in hours between my date and the time now.

This is my current string

v := "2014-05-03 20:57 UTC"

网友答案:

Use time.Parse and time.Since:

package main

import (
    "fmt"
    "time"
)

const (
    // See http://golang.org/pkg/time/#Parse
    timeFormat = "2006-01-02 15:04 MST"
)

func main() {
    v := "2014-05-03 20:57 UTC"
    then, err := time.Parse(timeFormat, v)
    if err != nil {
        fmt.Println(err)
        return
    }
    duration := time.Since(then)
    fmt.Println(duration.Hours())
}
网友答案:

Have a look at the time package.

package main

import "fmt"
import "time"

func main() {
    a, err := time.Parse("2006-01-02 15:04 MST", "2014-05-03 20:57 UTC")
    if err != nil {
        // ...
        return
    }

    delta := time.Now().Sub(a)
    fmt.Println(delta.Hours())
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: