time.ParseDuration() Function in Golang With Examples

Go language provides inbuilt support for measuring and displaying time with the help of the time package. In this package, the calendrical calculations always assume a Gregorian calendar with no leap seconds. This package provides a ParseDuration() function which parses a duration string. Duration string is a signed sequence of decimal numbers with optional fraction and unit suffix, like “100ms”, “2.3h” or “4h35m”. To access ParseDuration() function you need to add a time package in your program with the help of the import keyword.

Note: Valid time units are “ns”, “us” (or “µs”), “ms”, “s”, “m”, “h”.

Syntax:

func ParseDuration(str string) (Duration, error)

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// how to find time duration
package main
  
import (
    "fmt"
    "time"
)
  
func main() {
  
    // Using ParseDuration() function
    hr, _ := time.ParseDuration("3h")
    comp, _ := time.ParseDuration("5h30m40s")
  
    fmt.Println("Time Duration 1: ", hr)
    fmt.Println("Time Duration 2: ", comp)
  
}

chevron_right


Output:

Time Duration 1:  3h0m0s
Time Duration 2:  5h30m40s

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate
// how to find time duration
package main
  
import (
    "fmt"
    "time"
)
  
func main() {
  
    // Using ParseDuration() function
    hr, _ := time.ParseDuration("5h")
    comp, _ := time.ParseDuration("2h30m40s")
    m1, _ := time.ParseDuration("3µs")
    m2, _ := time.ParseDuration("3us")
  
    fmt.Println("Time Duration 1: ", hr)
    fmt.Println("Time Duration 2: ", comp)
    fmt.Printf("There are %.0f seconds in %v.\n",
                            comp.Seconds(), comp)
      
    fmt.Printf("There are %d nanoseconds in %v.\n",
                              m1.Nanoseconds(), m1)
      
    fmt.Printf("There are %6.2e seconds in %v.\n",
                                 m2.Seconds(), m1)
}

chevron_right


Output:

Time Duration 1:  5h0m0s
Time Duration 2:  2h30m40s
There are 9040 seconds in 2h30m40s.
There are 3000 nanoseconds in 3µs.
There are 3.00e-06 seconds in 3µs.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.