You are here:

C++/difference between times given in the format hh:mm AM/PM

Advertisement


Question
how to find the difference between two times given in the format hh:mm AM/PM, and the output should be in the format x hrs and y min.


Answer
There is a function in the C++ time class that allows you to find the difference between times.  First of all I do not understand what AM and PM has to do with a difference in time.  You will have to decipher that yourself.  The function takes two "raw" times and returns the difference as a double in seconds.  I looked for a function that would return the exact format you asked for, but I did not find one that gave the results using double input.

http://www.cplusplus.com/reference/clibrary/ctime/difftime.html

/* difftime example */
#include <stdio.h>
#include <time.h>

int main ()
{
 time_t start,end;
 char szInput [256];
 double dif;

 time (&start);
 printf ("Please, enter your name: ");
 gets (szInput);
 time (&end);
 dif = difftime (end,start);
 
 printf ( "%d:%d" , dif / 3600 , ( dif % 3600 ) / 60 ) ;

There is a time class function that puts time in the format you want (strftime), but it does not take double and it does not take the difference of times: http://www.cplusplus.com/reference/clibrary/ctime/strftime.html

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Titus B. Ledbetter, Jr.

Expertise

C , MFC, Object Oriented, Artificial Intelligence

Experience

I have over ten years experience in the field of Computer Science, five years experience developing C/C++. I recently wrote a chess program using Object Oriented, C++, MFC.

Education/Credentials
Master's Degree Computer Science from Johns Hopkins

©2016 About.com. All rights reserved.