You are here:

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


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.

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.

/* 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:


All Answers

Answers by Expert:

Ask Experts


Titus B. Ledbetter, Jr.


C , MFC, Object Oriented, Artificial Intelligence


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.

Master's Degree Computer Science from Johns Hopkins

©2017 All rights reserved.