从 golang 中的 gorm create at 中减去时间

subtract time now from gorm create at in golang

我正在尝试查找现在与数据库中创建于列的时间之间的时差

我return数据库中的一行,我有created_at列,时间格式如下

{"id":1,"email":"fUPvyBA@FApYije.ru","timezone":"pacific time","created_at":"2022-01-23T02:45:01.241589Z","updated_at":"2022-01-23T02:46:01.241591Z"}

所以created_at = 2022-01-23T02:45:01.241589Z

time.Now() = 2022-01-24 03:24:56.215573343 +0000 UTC m=+1325.103447033

我测试了以下内容

import (
    "fmt"
    "time"
)

func TestTime() {

    timestart := "2022-01-23T02:45:01.241589Z"
    timeend := time.Now()
    timediff := timeend.Sub(timestart)
    fmt.Println("time diff is: ", timediff.Seconds())
    
}

TestTime()

但我收到以下错误

cannot use <string> as <time.Time> in argument to timeend.Sub

如何减去我存储在 created_at 列中的时间与当前时间 time.Now() 之间的差异?

错误意味着您试图在 time.Time 参数上使用字符串

试试这个:

import (
    "fmt"
    "time"
)

func TestTime() {
    layout := time.RFC3339 // "2006-01-02T15:04:05Z07:00"
    timestart, err := time.Parse(layout, "2022-01-23T02:45:01.241589Z")
    
    if err != nil {
        panic(err)
    }
    
    timeend := time.Now()
    timediff := timeend.Sub(timestart)
    fmt.Println("time diff is:", ltimediff.Seconds())
    
}

TestTime()