Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time in seconds with time.Since

Tags:

time

go

I have a following function which calculated time since startTime, uptime: time.Since(startTime).String().

This returns time as follows:

"uptime": "3m54.26744075s"

How do I convert time to be in seconds, as follows:

"uptime": "123456789"
like image 659
moriol Avatar asked Dec 24 '22 10:12

moriol


1 Answers

time.Since() returns you a value of type time.Duration which has a Duration.Seconds() method, just use that:

secs := time.Since(startTime).Seconds()

This will be of type float64. If you don't need the fraction part, just convert it to int, e.g. int(secs). Alternatively you may divide the time.Duration value with time.Second (which is the number of nanoseconds in a second), and you'll get to an integer seconds value right away:

secs := int(time.Since(startTime) / time.Second)

(Note that the int conversion in this last example is not to drop the fraction part because this is already an integer division, but it's rather to have the result as a value of type int instead of time.Duration.)

Also see related question: Conversion of time.Duration type microseconds value to milliseconds

like image 178
icza Avatar answered Jan 03 '23 08:01

icza