Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing a time.Duration in Golang

Tags:

go

At present, the time package in Go has no 'divide' function or anything similar. You can divide a time.Duration by some other value, but it requires a fair bit of casting. Is there any easy/obvious way to divide a time.Duration by something in Go that I'm not seeing? (I know you can divide by a numeric constant, but I need to do it on a dynamic basis.) I'm planning on submitting a issue/feature request to add a basic 'divide' function to the time package, but I wanted to ask here first in case I'm missing some easy way to do this kind of division.

like image 983
Patrick Jones Avatar asked Feb 20 '19 00:02

Patrick Jones


1 Answers

Package time

import "time" 

There is no definition for units of Day or larger to avoid confusion across daylight savings time zone transitions.

To count the number of units in a Duration, divide:

second := time.Second
fmt.Print(int64(second/time.Millisecond)) // prints 1000

To convert an integer number of units to a Duration, multiply:

seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s

const (
        Nanosecond  Duration = 1
        Microsecond          = 1000 * Nanosecond
        Millisecond          = 1000 * Microsecond
        Second               = 1000 * Millisecond
        Minute               = 60 * Second
        Hour                 = 60 * Minute
)

type Duration

A Duration represents the elapsed time between two instants as an int64 nanosecond count. The representation limits the largest representable duration to approximately 290 years.

type Duration int64

Division and multiplication of time.Duration is described in the Go time package documentation.

like image 116
peterSO Avatar answered Sep 26 '22 04:09

peterSO