C++ Online Compiler
Example: Calculate the Difference Between Two Time Periods in C++ using time.h
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// 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 Initialize the first time (YYYY-MM-DD HH:MM:SS) time1.tm_year = 2025 - 1900; // Year since 1900 time1.tm_mon = 4; // May (0-based index) time1.tm_mday = 1; time1.tm_hour = 10; time1.tm_min = 30; time1.tm_sec = 0; // Step-3 Initialize the second time 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 both structures to time_t (epoch time) time_t t1 = mktime(&time1); time_t t2 = mktime(&time2); // Step-5 Find the difference in seconds double seconds = difftime(t2, t1); // Step-6 Convert seconds to hours, minutes, seconds int hours = seconds / 3600; int minutes = ((int)seconds % 3600) / 60; int remainingSeconds = (int)seconds % 60; // Step-7 Display the result cout << "\nTIME DIFFERENCE: " << hours << " HOURS, " << minutes << " MINUTES, " << remainingSeconds << " SECONDS\n"; return 0; }
Output
Clear
ADVERTISEMENTS