date - golang 中过去日期时间和当前时间之间的差异(以分钟为单位)

标签 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)

提前致谢:)

最佳答案

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

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

关于date - golang 中过去日期时间和当前时间之间的差异(以分钟为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52746225/

相关文章:

date - 删除日期后的所有文件,代码很慢

c++ - 以毫秒为单位的本地时间

javascript - 戈朗 : html pages and GO communication

go - time.Duration * time.Duration 应用了两次

go - 如何批量更改 GO 包别名?

javascript - 本地使用 Node.js 时不同的客户端和服务器时间

javascript - 如何告诉 JavaScript Date 从哪里获取 TimezoneOffset?

php - 一旦我计算出要输出的两位数应该不同,那么php中的excel表

MySQL多次引用同一个表

mysql - 在 MySQL 中将间隔格式化为 'yyyy-mm-dd hh:MM:ss'