How to get the difference between two dates in seconds with Go

2 Answers

0 votes
package main

import (
	"fmt"
	"time"
)

func main() {
	startDate := time.Date(2025, time.January, 12, 0, 0, 0, 0, time.UTC)
	endDate := time.Date(2025, time.January, 13, 0, 0, 0, 0, time.UTC)

	duration := endDate.Sub(startDate)

	seconds := int(duration.Seconds())

	fmt.Printf("The difference between the two dates is %d seconds\n", seconds)
}




/*
run:

The difference between the two dates is 86400 seconds

*/

 



answered Jan 13, 2025 by avibootz
0 votes
package main

import (
	"fmt"
	"time"
)

/**
 * Calculates the total number of seconds between two time.Time instances.
 * Returns a float64 to preserve fractional seconds (milliseconds, microseconds, etc.).
 */
func GetSecondsBetween(startDate, endDate time.Time) float64 {
	// Subtracting two time.Time values returns a time.Duration representing the interval
	duration := endDate.Sub(startDate)

	// .Seconds() converts the entire duration into seconds as a float64
	return duration.Seconds()
}

func main() {
	// Define two time.Time instances (best practice: explicitly define locations/UTC to avoid ambiguity)
	startDate := time.Date(2026, time.October, 27, 12, 0, 0, 0, time.UTC)
	endDate := time.Date(2026, time.October, 27, 12, 5, 30, 0, time.UTC)

	// Call the function to calculate the seconds between the two dates
	totalSeconds := GetSecondsBetween(startDate, endDate)

	// Output the results to the console using RFC3339 formatting
	fmt.Printf("Start Date: %s\n", startDate.Format(time.RFC3339))
	fmt.Printf("End Date:   %s\n", endDate.Format(time.RFC3339))
	fmt.Printf("Total Seconds Between: %.2f\n", totalSeconds)
}


/*
run:

Start Date: 2026-10-27T12:00:00Z
End Date:   2026-10-27T12:05:30Z
Total Seconds Between: 330.00

*/

 



answered Oct 27 by avibootz
...