Click here to Skip to main content
15,911,030 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I Have created a program to find time difference between start time and end time.How to calculate the time difference as I am not getting the right difference?

********************************

C++
#include<iostream.h>
#include<conio.h>
class time
{
   int hour;
   int minute;
   int second;
   public:
      time()
      {
         hour=0;
         minute=0;
         second=0;
      }
      void get_time()
      {
         cout<<"*********** START TIME/END TIME ***********"<<endl;
         cout<<"Enter Hour:";
         cin>>hour;
         cout<<"Enter Minute:";
         cin>>minute;
         cout<<"Enter Second:";
         cin>>second;
         cout<<endl;
      }
      friend void operator-(time,time);
};
void operator-(time t,time s)
{
   int a,b,c;
   a=t.hour-s.hour;
   b=t.minute-s.minute;
   c=t.second-s.second;
   cout<<"Difference Between Start Time & End Time="<<a<<"-"<<b<<"-"<<c<<endl;
}
int main()
{
   clrscr();
   time st,et;
   st.get_time();
   et.get_time();
   st-et;
   getch();
   return 0;
}
Posted
Updated 11-Mar-14 6:12am
v3

1 solution

Don't try to work out a time difference by assuming that you can subtract hours from hours, minutes from minutes and so on.

Think about it: how do you work out 45 minutes ago? By subtracting 45 from the current minutes and winding teh hour back if necessary.

The easest way to do this is to convert both times into a number of seconds:
C++
totalSeconds = ((hours * 60 + minutes) * 60) + seconds

Then subtract one from the other, and convert the result back to minutes, and then hours by divide and modulus by 60.
 
Share this answer
 
Comments
AP900 12-Mar-14 11:47am    
I Solved it..Thank you..
OriginalGriff 12-Mar-14 12:19pm    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900