过去日期时间与当前时间之间的时差,以golang为单位

时间:2018-10-10 18:00:20

标签: date go time

我有当前时间和过去时间,我试图在几分钟内找出差异。

这是我正在尝试的代码,尽管我是新手。

package main

import (
    "fmt"
    "time"
)

func main() {
    //fetching current time
    currentTime := time.Now().Format("2006-01-02 15:04:05")
    //past time comes in as string
    pasttimestr := "2018-10-10 23:00"
    layout := "2006-01-02 15:04:05"
    //converting string to date
    pasttime, err := time.Parse(layout, pasttimestr)
        if err != nil {
        fmt.Println(err)
    }
    //differnce between pastdate and current date
    diff := currentTime.Sub(pasttime)
    fmt.Println("difference time in min : ", diff)
}

错误:

# command-line-arguments
.\dates.go:21:21: currentTime.Sub undefined (type string has no field or method Sub)

预先感谢:)

2 个答案:

答案 0 :(得分:2)

您可能应该从当前时间删除format函数调用,以获取实际的时间结构而不是字符串表示形式,并修复过去时间的布局

package main

import (
    "fmt"
    "time"
)

func main() {
    //fetching current time
    currentTime := time.Now()
    loc := currentTime.Location()
    //past time comes in as string
    pasttimestr := "2018-10-10 23:00"
    layout := "2006-01-02 15:04"
    //converting string to date
    pasttime, err := time.ParseInLocation(layout, pasttimestr, loc)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("Past Time: ", pasttime)
    fmt.Println("Current Time: ", currentTime)
    //differnce between pastdate and current date
    diff := currentTime.Sub(pasttime)
    fmt.Printf("time difference is %v or %v in minutes\n", diff, diff.Minutes())
}

给我

Past Time:  2018-10-10 23:00:00 -0400 EDT
Current Time:  2018-10-10 14:31:34.865259 -0400 EDT m=+0.000351797
time difference is -8h28m25.134741s or -508.41891235 in minutes

答案 1 :(得分:1)

如下所示,将.Format()函数调用放到time.Now()上。另外,我还更新了layout string以使其与pasttimestr的格式匹配。

func main() {
    //fetching current time
    currentTime := time.Now()
    //past time comes in as string
    pasttimestr := "2018-10-10 23:00"
    layout := "2006-01-02 15:04"
    //converting string to date
    pasttime, err := time.Parse(layout, pasttimestr)
        if err != nil {
        fmt.Println(err)
    }
    //differnce between pastdate and current date
    diff := currentTime.Sub(pasttime)
    fmt.Println("difference time is : ", diff)
}

输出

difference time is :  -4h36m32.001213s