golang

What is time differences in GoLang?


In this article, you are going to learn about what is time differences in the Go language.

GoLang provides time packages to work with the time and in this package, you will get the functionality to determine a time and also see it. We will see the time differences between two variables with the help of this time package of the Go language. Before doing that, let’s see an example of using the time package and printing the current time in the console.

package main

import (
        "fmt"
        "time"
)

func main() {
        currentTime := time.Now()
        fmt.Println(currentTime)
}

// Output: 2021-12-31 16:25:40.637683 +0600 +06 m=+0.002873801

We have used time.Now() function that comes with the time package to print the current time. Try this code snippet to see the current local time of yours.We have used time.Now() function to get the current time. Similarly, there’s another function to see the time differences in the Go language that is sub(). This function also comes with a time package and it shows the result as int64 nanoseconds. Let’s see an example of it in the below:

package main

import (
        "time"
)

func main() {
        currentTime := time.Now()
        previousTime := time.Date(2021, 12, 31, 0, 0, 0, 0, time.UTC)
        difference := currentTime.Sub(previousTime)

        println(difference)
}

// Output: 38794373916000

You can see the proper time in hours, seconds, minutes, and seconds by using fmt packages. To do so see the code example below:

package main

import (
        "fmt"
        "time"
)

func main() {
        currentTime := time.Now()
        previousTime := time.Date(2021, 12, 31, 0, 0, 0, 0, time.UTC)
        difference := currentTime.Sub(previousTime)

        fmt.Println(difference)
}

// Output: 10h50m22.7692506s

This Sub() function also lets you see the differences into hours, minutes, seconds and, nanoseconds specifically. Let’s see the difference into minutes in the below:


package main

import (
        "fmt"
        "time"
)

func main() {
        currentTime := time.Now()
        previousTime := time.Date(2021, 12, 31, 0, 0, 0, 0, time.UTC)
        difference := currentTime.Sub(previousTime)

        fmt.Println(difference.Minutes())
}

// Output: 652.8226461183333

To see the time differences into minutes we used differnces.Minutes() that comes with the Sub() function and this is how you can see the time differences in the Go Language and your task is to try to print the current local time and see the differences into hours, seconds and, milliseconds.


Share on social media

//