moriol
moriol

Reputation: 69

Time in seconds with time.Since

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"

Upvotes: 5

Views: 11745

Answers (1)

icza
icza

Reputation: 418505

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

Upvotes: 13

Related Questions