Golang, get the difference between two times in seconds

Hi Friends 👋,

Welcome To aGuideHub! ❤️

To get the difference between two times in seconds,

  1. subtract times using the time Sub() method.
  2. Use the Seconds() method to get difference time in seconds.

Today, I’m going to show you how do you get the difference between two times in seconds in golang, here we will use the golang time.Sub() method to subtract time, and time.Seconds() to get the difference in seconds.

Let’s start today’s tutorial How do I get difference between two times in seconds in golang?

Here, we are going to do,

  1. Define two date times object.
  2. Use Sub() to get difference time.
  3. Use the Seconds() method to get the difference in seconds.
package main

import (
    "fmt"
    "time"
)

func main() {
    currentTime := time.Now()
    oldTime := time.Date(2020, 1, 2, 0, 0, 0, 0, time.UTC)
    diff := currentTime.Sub(oldTime)

    //In seconds
    fmt.Printf("Seconds: %f\n", diff.Seconds())
}

The above program will print a number of seconds between two dates in the golang console, let’s check the output.

diff Seconds, golang

Try it yourself

All the best 👍

Premium Content

You can get all the below premium content directly in your mail when you subscribe us

Books

Interview Questions

Soon You will get CSS, JavaScript, React Js, and TypeScript So Subscribe to it.

Portfolio Template

View | Get Source Code

Cheat Sheets

Cheat Sheets Books are basically Important useful notes which we use in our day-to-day life.

Related Posts