英文:
subtract time now from gorm create at in golang
问题
我正在尝试计算当前时间与数据库中的created_at
列之间的时间差。
我从数据库中返回了一行数据,其中包含以下时间格式的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()
之间的差异?
英文:
I am trying to do find the time difference between time now from the created at column in the database
I return a row in the database, i have the created_at
column with the following time format
{"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"}
so created_at
= 2022-01-23T02:45:01.241589Z
and
time.Now()
= 2022-01-24 03:24:56.215573343 +0000 UTC m=+1325.103447033
I tested with the following
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()
but i get the following errors
cannot use <string> as <time.Time> in argument to timeend.Sub
How do i subtract to get the difference between the time i stored in created_at
column from the current time time.Now()
?
答案1
得分: 1
错误意味着您试图在一个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("时间差是:", timediff.Seconds())
}
TestTime()
这段代码将解析一个字符串时间并计算与当前时间的时间差。
英文:
The error means that you trying to use an string on a time.Time parameter
Try this:
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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论