Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between two given time periods in C++
Problem Statement
Given two time periods in the string 'HH:MM: SS' format. Here 'HH' represents hours, 'MM' represents minutes and 'SS' represents seconds. Find the difference in the same string format between these two time periods.
Time period 1 = 8:6:2 Time period 2 = 3:9:3 Time Difference is 4:56:59
Example
Following is the program in C++ to find the required output.
#include <iostream>
using namespace std;
int main() {
int hour1, minute1, second1;
int hour2, minute2, second2;
int diff_hour, diff_minute, diff_second;
cout << "Enter time period 1" << endl;
cout << "Enter hours, minutes and seconds respectively: "<< endl;
cin >> hour1 >> minute1 >> second1;
cout << "Enter time period 2" << endl;
cout << "Enter hours, minutes and seconds respectively: "<< endl;
cin >> hour2 >> minute2 >> second2;
if(second2 > second1) {
minute1--;
second1 += 60;
}
diff_second = second1 - second2;
if(minute2 > minute1) {
hour1--;
minute1 += 60;
}
diff_minute = minute1 - minute2;
diff_hour = hour1 - hour2;
cout <<"Time Difference is "<< diff_hour <<":"<< diff_minute <<":"<<diff_second;
return 0;
}
Output
Enter time period 1 Enter hours, minutes and seconds respectively: 7 6 2 Enter time period 2 Enter hours, minutes and seconds respectively: 5 4 3 Time Difference is 2:1:59
Advertisements