简体   繁体   中英

Dividing a time.Duration in Golang

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.

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.

If the divisor is a multiple of two, you can use shifting instead, without any casting:

package main

import (
   "fmt"
   "time"
)

func main() {
   n := 1
   d := time.Minute >> n
   fmt.Println(d) // 30s
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM