Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

subtract time now from gorm create at in golang

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading