Menu Close

Go – How to convert time duration into nanoseconds in Go

Here, we are going to learnĀ about how to convert time duration into nanoseconds in Go. We will learn it by example and program.

Nanoseconds() method of time package will be used to convert time duration into nanoseconds in Go.

Function prototype:

func (d Duration) Nanoseconds() int64

Input parameters:


Duration: type Duration int64

Return value:

Nanoseconds() function in time package returns the duration as an integer nanosecond count.

Example with code:

package main

import (
        "fmt"
        "time"
)

func main() {

        h, _ := time.ParseDuration("2h30m")

        fmt.Printf("Convert 2 hour 30 minutes to Nanoseconds: %d\n", h.Nanoseconds())

        h, _ = time.ParseDuration("2s")

        fmt.Printf("Convert 2 seconds to Nanoseconds: %d\n", h.Nanoseconds())

        h, _ = time.ParseDuration("30m")

        fmt.Printf("Convert 30 minutes to Nanoseconds: %d\n", h.Nanoseconds())

}

Output:

 Convert 2 hour 30 minutes to Nanoseconds: 9000000000000

 Convert 2 seconds to Nanoseconds: 2000000000

 Convert 30 minutes to Nanoseconds: 1800000000000

To learn more about golang, Please refer given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, time

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *