Calculating the Difference Between Two Time Periods in Go
Go (or Golang) is known for its simplicity and speed, making it a great choice for systems programming and concurrent applications.
When dealing with time-based data in Go
, the time
package provides robust support for manipulating dates, times, and durations.
In this sub-article, we’ll demonstrate how to calculate the difference between two time periods in Go. This example builds on the concepts discussed in our C lead article, but utilizes Go's native time
package for accurate and efficient calculations.
Required Package
To work with time in Go, you'll need the time
package:
import "time"
Go Program: Calculate the Difference Between Two Time Periods
// DIFFERENCE BETWEEN TWO TIME PERIODS in Go using time package
package main
import (
"fmt"
"time"
)
func main() {
// Step-1 Define the start and end time using time.Date
startTime := time.Date(2025, time.July, 4, 9, 15, 20, 0, time.UTC)
endTime := time.Date(2025, time.July, 12, 18, 30, 10, 0, time.UTC)
// Step-2 Calculate the difference
duration := endTime.Sub(startTime)
// Step-3 Extract hours, minutes, and seconds
hours := int(duration.Hours())
minutes := int(duration.Minutes()) % 60
seconds := int(duration.Seconds()) % 60
// Step-4 Display the result
fmt.Printf("\nTIME DIFFERENCE: %d HOURS, %d MINUTES, %d SECONDS\n", hours, minutes, seconds)
}
Output
TIME DIFFERENCE: 207 HOURS, 14 MINUTES, 50 SECONDS
Explanation
-
The
time.Date()
function is used to define the starting and ending timestamps with the year, month, day, hour, minute, second, and location (time zone). -
The
Sub()
method calculates the difference between the two
objects, returning atime
.TimeDuration
. -
We extract the duration in hours, minutes, and seconds for display.
This approach in Go is efficient and works well in a variety of applications, especially when performance is critical, such as in high-frequency trading or real-time systems.
Extra Metric: Duration in Days
To compute the duration in days, you can use:
days := int(duration.Hours() / 24)
fmt.Printf("TOTAL DAYS: %d\n", days)
Output
TOTAL DAYS: 8
This is particularly useful when working with long durations, such as calculating the number of days between two events for scheduling or logging.