Solved

Subtract time from another time

Posted on 2003-11-20
8
468 Views
Last Modified: 2010-04-15
this program is to subtract time from another time in 24 hour format. eg. 1hr 0mins - 1hr 30mins should read 23.30.
however in my program when it works out it reads 1-1 = 0 and not 23.  
any ideas? thanks

#include <stdio.h>

void main (void){
      
int hours1, hours2, mins1, mins2;

      printf("Please enter what hour it is: ");
      scanf("%d", &hours1);
      fflush(stdin);

      printf("Please enter how many minutes have passed: ");
      scanf("%d", &mins1);

      printf("Please enter hour 2: ");
      scanf("%d", &hours2);
      fflush(stdin);

      printf("Please enter how many minutes have passed: ");
      scanf("%d", &mins2);


      printf("Answer time is : %d:%d\n", (hours1 - hours2), (mins1 - mins2));

}
0
Comment
Question by:pete420
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
8 Comments
 
LVL 45

Expert Comment

by:Kent Olsen
ID: 9790405

There are a lot of ways to solve this problem.  Instinctively, our brains want to subtract two time values just as we do two integers.  But the "borrow" can get a little bit messy because the time format of Hh:Mm.  When subtracting column m, if a borrow is necessary we decrement M and add 10 the smaller value.  When subtracting column M, we decrement h and add 6 to M.

It becomes an excercise in programming that we learn to avoid.

The easiest way is to convert each time value to a common integer value.  In this case, the number of minutes per day (24*60=1440) works well, so does the number of seconds per day (24*60*60=86400).  Then subtract the two integers and convert back to HH:mm

Here are the formulas.  Since this sounds like homework, you'll have to plug them in yourself:

MinuteValue = Hours * 60 + Minutes;  // Convert HH:MM to minutes

Hh = MinuteValue / 60;
Mm = MinuteValue % 60;


Good Luck,
Kent

0
 
LVL 45

Expert Comment

by:Kent Olsen
ID: 9790502

Hi Pete420,

Your program doesn't deal with input values very well.  Here's a style that is a bit more useful:

#define BUFFL 1024

#include <stdlib.h>

void main (void){
  char Buffer[BUFFL];  
  int hours1, hours2, mins1, mins2;
  int time1, time2;

      printf("Please enter the first time (hh:mm): ");
     fgets (Buffer, BUFFL, stdin);
     hours1 = mins1 = -1;
     scanf (Buffer, "%d:%d", &hours1, &mins1);
     if (hours1 < 0 || hours1 > 23 || mins1 < 0 || mins 1 > 59)
     {
       printf ("You did not enter a valid date\n");
       exit (0);
     }

     printf("Please enter the second time (hh:mm): ");
     fgets (Buffer, BUFFL, stdin);
     hours1 = mins1 = -1;
     scanf (Buffer, "%d:%d", &hours2, &mins2);
     if (hours2 < 0 || hours2 > 23 || mins2 < 0 || mins2 > 59)
     {
       printf ("You did not enter a valid date\n");
       exit (0);
     }

    time1 = hours1 * 60 + mins1;
    time2 = hours2 * 60 + mins2;

/*
    Just in case this is homework, I really can't write the entire program for you.  :)
    Subtracting time2 from time1 will give you the number of minutes that have elapsed.

    Convert the difference into HH:MM format with the equations that I gave you in my first post and display them.
*/
}


Kent
0
 
LVL 19

Expert Comment

by:Dexstar
ID: 9790608
@pete420:

> this program is to subtract time from another time in 24 hour format. eg. 1hr
> 0mins - 1hr 30mins should read 23.30. however in my program when it works out
> it reads 1-1 = 0 and not 23.  
> any ideas? thanks

I would use the C standard library to accomplish this.  The functions you need are basically "gmtime" and "mktime".  This page has good info:  http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.15.html

Here is your program re-written to use those functions:
      #include <stdio.h>
      #include <time.h>

      void main (void)
      {
            struct tm theTime;
            int nHours, nMinutes;
            time_t tTemp;

            /* Start with the current time */
            time( &tTemp );
            memcpy( &theTime, gmtime(&tTemp), sizeof(theTime) );
            theTime.tm_isdst = -1; /* Set DST */
            theTime.tm_sec = 0;

            /* Read the start time */
            printf("Please enter what hour it is: ");
            scanf("%d", &theTime.tm_hour);
            fflush(stdin);

            printf("Please enter how many minutes have passed: ");
            scanf("%d", &theTime.tm_min);
            
            /* Read the elapsed time */
            printf("Please enter hour 2: ");
            scanf("%d", &nHours);
            fflush(stdin);

            printf("Please enter how many minutes have passed: ");
            scanf("%d", &nMinutes);

            /* Adjust the time */
            theTime.tm_hour -= nHours;
            theTime.tm_min -= nMinutes;
            mktime(&theTime);

            /* Display the result */
            printf("Answer time is : %d:%d\n", theTime.tm_hour, theTime.tm_min);
      }

Hope That Helps,
Dex*
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:pete420
ID: 9790858
my updated code now reads. however im still gettin the wrong answer. ken thanks for the advice on the better input way however im  not sure of every feature so i think it best not 2 use it.  dexstar, altho ur way seems to be a gd way to solve this problem again i am not sure of the functions.

#include <stdio.h>

void main (void){
      
int hours1, hours2, mins1, mins2, Hh, Mm, time1, time2, minval;

      printf("Please enter what hour it is: ");
      scanf("%d", &hours1);
      fflush(stdin);

      printf("Please enter how many minutes have passed: ");
      scanf("%d", &mins1);

      printf("Please enter hour 2: ");
      scanf("%d", &hours2);
      fflush(stdin);

      printf("Please enter how many minutes have passed: ");
      scanf("%d", &mins2);

      time1 = hours1 * 60 +mins1;
      printf("time1 %d", time1);
      time2= hours2 * 60+ mins2;
      printf("time2 %d", time2);
      minval = time1 - time2;

      Hh = minval / 60;
      Mm = minval % 60;

       printf("Answer time is : %d:%d\n", Hh, Mm);

}
0
 
LVL 19

Expert Comment

by:Dexstar
ID: 9790954
Just try the code that I posted, and then ask me about the parts that you do not understand...

The key of it is the mktime function (More Info: http://www.unidata.ucar.edu/cgi-bin/man-cgi?mktime+3).  It will correct a struct that contains the time values to be correct.  Here's how the program works:

1) It fills in the time structure with the current time and date information.
2) I change the hour and minute parts of the time to be the first hour and minute entered by the user.
So, with your sample data, then:
     theTime.tm_hour = 1;
     theTime.tm_min = 0;
(The other date information will have today's date)

Then, I subtract off the other hour and minute from those values, so with your sample data:
     theTime.tm_hour = 0;
     theTime.tm_min = -30;

Clearly that looks wrong because you can't have -30 minutes!  But, after you do that, if you call "mktime", it will "correct" your struct to have the correct time.  It will look like this:
     theTime.tm_hour = 23;
     theTime.tm_min = 30;
And the date information will be from YESTERDAY!

Just try the code I gave you... I tested it and everything, it should work just fine.

Dex*

0
 

Author Comment

by:pete420
ID: 9791271
yes ur solution works first class however i cannot use it for this assignment due to none of the features being mentioned before. thanks loads for the help but i think ken's solution is more along the lines of what is expected.. any ideas of how to do it that way?
0
 
LVL 19

Accepted Solution

by:
Dexstar earned 250 total points
ID: 9791386
Oh, that was for an assignment?  You didn't mention that...  :|

Okay, so I would do everything in terms of minutes, and then convert back at the end.  Like in these steps:

1) Compute the time in terms of minutes
     nTotalMinutes = (hours1*60 + minutes1) - (hours2*60 + minutes2);

2) Correct if negative, by adding to total number of minutes in a day, like this:
     while ( nTotalMinutes < 0 ) nTotalMinutes += (60*24);

3) Compute the values to display:
     nHours = nTotalMinutes / 60;
     nTotalMinutes -= (nHours*60);

printf("Answer time is : %d:%d\n", nHours , nTotalMinutes );


0
 

Author Comment

by:pete420
ID: 9791435
Cheers man! works a treat!
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
Examines three attack vectors, specifically, the different types of malware used in malicious attacks, web application attacks, and finally, network based attacks.  Concludes by examining the means of securing and protecting critical systems and inf…
The goal of this video is to provide viewers with basic examples to understand and use conditional statements in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use switch statements in the C programming language.

617 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question