Calculating the Difference Between Two Time Periods in C
In programming, it's often necessary to calculate the difference between two time periods, whether it's to find the difference between two dates or subtract one time value from another.
In C, you can achieve this using the time.h
library, which provides the necessary tools to handle date and time manipulations.
Objective
In this article, we will calculate the difference between two time periods in C using the struct tm
structure, which represents a time and date. We'll follow a structured approach with clear steps and code comments.
Prerequisites
-
Basic understanding of C programming
-
Familiarity with the
time.h
library
Code Example
// Calculating the Difference Between Two Time Periods in C
#include <stdio.h>
#include <time.h>
// The main function of the program
int main()
{
// Step-1 Declare and initialize time variables
struct tm time1 = {0}; // Initializing time1 to zero
struct tm time2 = {0}; // Initializing time2 to zero
// Step-2 Input the first time period (time1)
time1.tm_year = 2025 - 1900; // tm_year is year since 1900
time1.tm_mon = 4; // Month is 0-based (0 = January)
time1.tm_mday = 1; // Day of the month
time1.tm_hour = 10; // Hour (24-hour format)
time1.tm_min = 30; // Minutes
time1.tm_sec = 0; // Seconds
// Step-3 Input the second time period (time2)
time2.tm_year = 2025 - 1900;
time2.tm_mon = 4;
time2.tm_mday = 9;
time2.tm_hour = 15;
time2.tm_min = 45;
time2.tm_sec = 0;
// Step-4 Convert struct tm to time_t for both time periods
time_t t1 = mktime(&time1);
time_t t2 = mktime(&time2);
// Step-5 Calculate the difference in seconds
double difference = difftime(t2, t1);
// Step-6 Convert the difference to hours, minutes, and seconds
int hours = difference / 3600; // 3600 seconds in an hour
int minutes = (difference - (hours * 3600)) / 60; // Remaining minutes
int seconds = difference - (hours * 3600) - (minutes * 60); // Remaining seconds
// Step-7 Output the result
printf("\nTime difference: %d hours, %d minutes, %d seconds\n", hours, minutes, seconds);
return 0;
}
Output
Time difference: 197 hours, 15 minutes, 0 seconds
Explanation of the Code:
-
Declare Time Variables: We declare two
variables (struct
tmtime1
andtime2
) to store the two time periods. -
Input Time Periods: We manually input values for
time1
andtime2
. The months are 0-based (i.e., 0 for January), so we subtract 1 when setting the month. -
Convert to
time_t
: We use themktime()
function to convert thestruct tm
into atime_t
value, which represents the time in seconds since the Unix epoch (January 1, 1970). -
Calculate the Difference: The
difftime()
function calculates the difference in seconds betweentime2
andtime1
. -
Convert to Human-Readable Format: We then calculate hours, minutes, and seconds from the difference in seconds.
-
Output the Result: Finally, we output the calculated time difference.
Output Example:
For the time periods 2025-05-01 10:30:00 and 2025-05-09 15:45:00, the output will be:
Examples in other languages
C++
// DIFFERENCE BETWEEN TWO TIME PERIODS in C++ using time.h
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
// Step-1 Declare two time structures
struct tm time1 = {0}, time2 = {0};
// Step-2 Assign values to both time structures
time1.tm_year = 2025 - 1900;
time1.tm_mon = 4;
time1.tm_mday = 1;
time1.tm_hour = 10;
time1.tm_min = 30;
time1.tm_sec = 0;
time2.tm_year = 2025 - 1900;
time2.tm_mon = 4;
time2.tm_mday = 9;
time2.tm_hour = 15;
time2.tm_min = 45;
time2.tm_sec = 0;
// Step-3 Convert tm to time_t
time_t t1 = mktime(&time1);
time_t t2 = mktime(&time2);
// Step-4 Calculate difference
double diff = difftime(t2, t1);
int hours = diff / 3600;
int minutes = ((int)diff % 3600) / 60;
int seconds = (int)diff % 60;
// Step-5 Print result
cout << "\nTIME DIFFERENCE: " << hours << " HOURS, " << minutes << " MINUTES, " << seconds << " SECONDS\n";
return 0;
}
Java
// DIFFERENCE BETWEEN TWO TIME PERIODS in Java using LocalDateTime
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// Step-1 Create two LocalDateTime instances
LocalDateTime time1 = LocalDateTime.of(2025, 5, 1, 10, 30, 0);
LocalDateTime time2 = LocalDateTime.of(2025, 5, 9, 15, 45, 0);
// Step-2 Calculate time difference
long diffInSeconds = ChronoUnit.SECONDS.between(time1, time2);
// Step-3 Convert to hours, minutes, seconds
long hours = diffInSeconds / 3600;
long minutes = (diffInSeconds % 3600) / 60;
long seconds = diffInSeconds % 60;
// Step-4 Print result
System.out.println("\nTIME DIFFERENCE: " + hours + " HOURS, " + minutes + " MINUTES, " + seconds + " SECONDS");
}
}
C#
// DIFFERENCE BETWEEN TWO TIME PERIODS in C# using DateTime
using System;
public class W3CW
{
public static void Main()
{
// Step-1 Define two DateTime variables
DateTime time1 = new DateTime(2025, 5, 1, 10, 30, 0);
DateTime time2 = new DateTime(2025, 5, 9, 15, 45, 0);
// Step-2 Get difference as TimeSpan
TimeSpan difference = time2 - time1;
// Step-3 Print time difference
Console.WriteLine("\nTIME DIFFERENCE: {0} HOURS, {1} MINUTES, {2} SECONDS",
difference.Hours + difference.Days * 24, difference.Minutes, difference.Seconds);
}
}
Python
# DIFFERENCE BETWEEN TWO TIME PERIODS in Python using datetime
from datetime import datetime
# Step-1 Define two datetime values
time1 = datetime(2025, 5, 1, 10, 30, 0)
time2 = datetime(2025, 5, 9, 15, 45, 0)
# Step-2 Get difference
diff = time2 - time1
total_seconds = diff.total_seconds()
# Step-3 Convert to hours, minutes, seconds
hours = int(total_seconds // 3600)
minutes = int((total_seconds % 3600) // 60)
seconds = int(total_seconds % 60)
# Step-4 Print result
print(f"\nTIME DIFFERENCE: {hours} HOURS, {minutes} MINUTES, {seconds} SECONDS")
JavaScript
// DIFFERENCE BETWEEN TWO TIME PERIODS in JavaScript using Date
const time1 = new Date(2025, 4, 1, 10, 30, 0); // Month is 0-indexed
const time2 = new Date(2025, 4, 9, 15, 45, 0);
// Step-1 Calculate difference in milliseconds
const diff = time2 - time1;
// Step-2 Convert to hours, minutes, seconds
const hours = Math.floor(diff / 3600000);
const minutes = Math.floor((diff % 3600000) / 60000);
const seconds = Math.floor((diff % 60000) / 1000);
// Step-3 Print result
console.log(`\nTIME DIFFERENCE: ${hours} HOURS, ${minutes} MINUTES, ${seconds} SECONDS`);
Go
// DIFFERENCE BETWEEN TWO TIME PERIODS in Go using time package
package main
import (
"fmt"
"time"
)
func main() {
// Step-1 Create two time values
time1 := time.Date(2025, 5, 1, 10, 30, 0, 0, time.UTC)
time2 := time.Date(2025, 5, 9, 15, 45, 0, 0, time.UTC)
// Step-2 Get difference in seconds
diff := time2.Sub(time1).Seconds()
// Step-3 Convert to hours, minutes, seconds
hours := int(diff) / 3600
minutes := (int(diff) % 3600) / 60
seconds := int(diff) % 60
// Step-4 Print result
fmt.Printf("\nTIME DIFFERENCE: %d HOURS, %d MINUTES, %d SECONDS\n", hours, minutes, seconds)
}
Rust
// DIFFERENCE BETWEEN TWO TIME PERIODS in Rust using chrono
use chrono::{NaiveDateTime};
fn main() {
// Step-1 Define two datetime values
let time1 = NaiveDateTime::parse_from_str("2025-05-01 10:30:00", "%Y-%m-%d %H:%M:%S").unwrap();
let time2 = NaiveDateTime::parse_from_str("2025-05-09 15:45:00", "%Y-%m-%d %H:%M:%S").unwrap();
// Step-2 Calculate difference
let diff = time2.signed_duration_since(time1).num_seconds();
// Step-3 Convert to hours, minutes, seconds
let hours = diff / 3600;
let minutes = (diff % 3600) / 60;
let seconds = diff % 60;
// Step-4 Print result
println!("\nTIME DIFFERENCE: {} HOURS, {} MINUTES, {} SECONDS", hours, minutes, seconds);
}
Swift
// DIFFERENCE BETWEEN TWO TIME PERIODS in Swift using Date
import Foundation
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let time1 = formatter.date(from: "2025-05-01 10:30:00")!
let time2 = formatter.date(from: "2025-05-09 15:45:00")!
let diff = time2.timeIntervalSince(time1)
let hours = Int(diff) / 3600
let minutes = (Int(diff) % 3600) / 60
let seconds = Int(diff) % 60
print("\nTIME DIFFERENCE: \(hours) HOURS, \(minutes) MINUTES, \(seconds) SECONDS")
Kotlin
// DIFFERENCE BETWEEN TWO TIME PERIODS in Kotlin using LocalDateTime
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
fun main() {
// Step-1 Define two datetime values
val time1 = LocalDateTime.of(2025, 5, 1, 10, 30, 0)
val time2 = LocalDateTime.of(2025, 5, 9, 15, 45, 0)
// Step-2 Calculate difference in seconds
val diff = ChronoUnit.SECONDS.between(time1, time2)
// Step-3 Convert to hours, minutes, seconds
val hours = diff / 3600
val minutes = (diff % 3600) / 60
val seconds = diff % 60
// Step-4 Print result
println("\nTIME DIFFERENCE: $hours HOURS, $minutes MINUTES, $seconds SECONDS")
}
PHP
// DIFFERENCE BETWEEN TWO TIME PERIODS in PHP using strtotime
<?php
$time1 = strtotime("2025-05-01 10:30:00");
$time2 = strtotime("2025-05-09 15:45:00");
$diff = $time2 - $time1;
$hours = floor($diff / 3600);
$minutes = floor(($diff % 3600) / 60);
$seconds = $diff % 60;
echo "\nTIME DIFFERENCE: $hours HOURS, $minutes MINUTES, $seconds SECONDS\n";
?>
Ruby
# DIFFERENCE BETWEEN TWO TIME PERIODS in Ruby using Time
require 'time'
time1 = Time.parse("2025-05-01 10:30:00")
time2 = Time.parse("2025-05-09 15:45:00")
diff = time2 - time1
hours = (diff / 3600).to_i
minutes = ((diff % 3600) / 60).to_i
seconds = (diff % 60).to_i
puts "\nTIME DIFFERENCE: #{hours} HOURS, #{minutes} MINUTES, #{seconds} SECONDS"
R
# DIFFERENCE BETWEEN TWO TIME PERIODS in R using difftime
time1 <- as.POSIXct("2025-05-01 10:30:00", tz = "UTC")
time2 <- as.POSIXct("2025-05-09 15:45:00", tz = "UTC")
diff <- as.numeric(difftime(time2, time1, units = "secs"))
hours <- diff %/% 3600
minutes <- (diff %% 3600) %/% 60
seconds <- diff %% 60
cat("\nTIME DIFFERENCE:", hours, "HOURS,", minutes, "MINUTES,", seconds, "SECONDS\n")
Scala
// DIFFERENCE BETWEEN TWO TIME PERIODS in Scala using LocalDateTime
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
object W3CW extends App {
val time1 = LocalDateTime.of(2025, 5, 1, 10, 30, 0)
val time2 = LocalDateTime.of(2025, 5, 9, 15, 45, 0)
val diff = ChronoUnit.SECONDS.between(time1, time2)
val hours = diff / 3600
val minutes = (diff % 3600) / 60
val seconds = diff % 60
println(s"\nTIME DIFFERENCE: $hours HOURS, $minutes MINUTES, $seconds SECONDS")
}
Conclusion
Using the time.h
library in C, calculating the difference between two time periods is simple and effective. By following the steps above, you can easily compute the difference in seconds, minutes, hours, or even days.
This technique is useful for various applications, including scheduling, event tracking, and date-time calculations.