C Online Compiler
Example: Calculating the Difference Between Two Time Periods in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// 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
Clear
ADVERTISEMENTS