C++ Online Compiler
Example: 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 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; }
Output
Clear
ADVERTISEMENTS