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()?
>Solution :
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()