Calculate time in C language - c

I am trying to calculate time in C language and i have the following program:
#include <stdio.h>
#include <time.h>
int main(void) {
int hours, minutes;
double diff;
time_t end, start;
struct tm times;
times.tm_sec = 0;
times.tm_min = 0;
times.tm_hour = 0;
times.tm_mday = 1;
times.tm_mon = 0;
times.tm_year = 70;
times.tm_wday = 4;
times.tm_yday = 0;
time_t ltt;
time(&ltt);
struct tm *ptm = localtime(&ltt);
times.tm_isdst = ptm->tm_isdst;
printf("Start time (HH:MM): ");
if((scanf("%d:%d", &times.tm_hour, &times.tm_min)) != 2){
return 1;
}
start = mktime(&times);
printf("End time (HH:MM): ");
if((scanf("%d:%d", &times.tm_hour, &times.tm_min)) != 2){
return 1;
}
end = mktime(&times);
diff = difftime(end, start);
hours = (int) diff / 3600;
minutes = (int) diff % 3600 / 60;
printf("The difference is %d:%d.\n", hours, minutes);
return 0;
}
The program works almost ok:
Output 1:
./program
Start time (HH:MM): 05:40
End time (HH:MM): 14:00
The difference is 8:20.
Output 2:
./program
Start time (HH:MM): 14:00
End time (HH:MM): 22:20
The difference is 8:20.
Output 3:
/program
Start time (HH:MM): 22:20
End time (HH:MM): 05:40
The difference is -16:-40.
As you can see, I got -16:-40 instead of 7:20.
I cannot figure out how to fix this.

If end is after midnight and start before, add 24 hours to the end value:
if( end < start )
{
end += 24 * 60 * 60 ;
}
diff = difftime(end, start);
Note too that all the code related to mktime and tm struct is unnecessary. Those are useful when you require time normalisation (for example if you set tm_hour to 25, mktime will generate a time_t value that is 0100hrs the following day, rolling over the month and year too if necessary), but here you are dealing with just time of day in hours and minutes, so you need just:
int hour ;
int minute ;
if((scanf("%d:%d", &hour, &minute)) != 2){
return 1;
}
start = (time_t)((hour * 60 + minute) * 60) ;
printf("End time (HH:MM): ");
if((scanf("%d:%d", &hour, &minute)) != 2){
return 1;
}
end = (time_t)((hour * 60 + minute) * 60) ;

Related

How do I properly compute and convert the starting time and ending time of the call in minutes?

The start and end time are based on a 24 hour clock format. The task is that we will input the start and the end time then we will compute the length of the call and convert the result in minutes.
Sample output:
Start time: 1810
End time: 2000
Length of call: 110 minutes
Here's what I did try doing. First, I tried to minus the start and end time and automatically turn the answer into positive. Now if the total result(resultMain) is greater than 120, it will multiply the result to (.60). Else if the result is greater than 60 and less than 120, then it will just get minus 40 instead of it getting multiplied by (.60). My problem is that my result is inconsistent, sometimes the answer is correct but sometimes it is wrong.
#include <stdio.h>
#include <math.h>
#include <string.h>
int main()
{
int startTime, endTime, result1, result2;
double totalTime1, totalTime2, resultMain;
printf("\nPLDT Telephone Call Charge\n");
printf("\nStart time\t: ");
scanf("%d", &startTime);
printf("End time\t: ");
scanf("%d", &endTime);
totalTime1 = startTime - endTime;
resultMain = fabs(totalTime1);
if(resultMain >= 120){
totalTime2 = resultMain * .60;
result1 = ceil(totalTime2);
result2 = fabs(result1);
printf("Length of call\t: %d minutes\n", result2);
}else if(resultMain >= 60 && resultMain < 120){
totalTime2 = resultMain - 40;
result1 = ceil(totalTime2);
result2 = fabs(result1);
printf("Length of call\t: %d minutes\n", result2);
}else{
totalTime2 = resultMain;
result1 = ceil(totalTime2);
result2 = fabs(result1);
printf("Length of call\t: %d minutes\n", result2);
}
return 0;
}
Example of correct answer:
Start time: 0123
End time: 0224
Length of call: 61 minutes
Example of wrong answer:
Start time: 0852
End time: 0906
Length of call: 54 minutes
Example of wrong answer:
Start time: 0805
End time: 1210
Length of call: 243 minutes
No need for any floating point math
Before subtracting, break time into hours and minutes
int startTime_hours = startTime/100;
int startTime_mins = startTime%100;
startTime_mins += startTime_hours*60; // startTime_mins is now the total minutes.
The difference is the end minus the start
int diff = endTime_mins - startTime_mins;
When difference is negative, add a day worth of time
Example: start time just before midnight and the end time after midnight.
if (diff < 0) {
diff += 24*60;
}
Only 1 case needed for printing
printf("Length of call\t: %d minutes\n", diff);
You can use this algorithm to calculate the difference in minutes between two times:
const MINS_PER_HR = 60, MINS_PER_DAY = 1440
startx = starthour * MINS_PER_HR + startminute
endx = endhour * MINS_PER_HR + endminute
duration = endx - startx
if duration < 0:
duration = duration + MINS_PER_DAY
See: Algorithm needed to calculate difference between two times
This code will implement it for you:
#include <stdio.h>
int main()
{
int startTime, endTime, startHour, startMin, endHour, endMin, duration;
printf("\nPLDT Telephone Call Charge\n");
printf("\nStart time\t: ");
scanf("%04d", &startTime);
printf("End time\t: ");
scanf("%04d", &endTime);
startHour = startTime / 100;
startMin = startTime % 100;
endHour = endTime / 100;
endMin = endTime % 100;
duration = (endHour * 60 + endMin) - (startHour * 60 + startMin);
if (duration < 0)
duration += 60 * 24;
printf("Length of call\t: %d minutes\n", duration);
return 0;
}

How to get the time difference between two times (24h format)

I am currently trying to create a program where the user gives two values (times, hh:mm:ss) and gets the difference between the two times. This works, if one would only use 12h formats; however, using the 24h format is a must.
My current time struct looks like the following:
typedef struct time {
int hours;
int minutes;
int seconds;
} time;
And my current function to calculate the difference looks like this:
time calculateTimeDiff(time time1, time time2) {
time timeResult;
timeResult.hours = time1.hours - time2.hours;
if(time1.minutes != 00 && time2.minutes != 00) {
timeResult.minutes = time1.minutes - time2.minutes;
}
else {
timeResult.minutes = 00;
}
if(time1.seconds != 00 && time2.seconds != 00) {
timeResult.seconds = time1.seconds - time2.seconds;
}
else {
timeResult.seconds = 00;
}
while(timeResult.seconds > 60) {
timeResult.seconds -= 60;
timeResult.minutes += 1;
}
while(timeResult.minutes > 60) {
timeResult.minutes -= 60;
timeResult.hours += 1;
}
return timeResult;
}
My attempts to support the 24h format have been to add 12 hours to the time if the hours "exceed" the 12 hour format, and to divide the time by two (haven't been far from complete shots in the dark, just to see what works and what wouldn't work). However, this has only resulted in getting incorrect results.
Any and all answers appreciated!
How to get the time difference between two times (24h format)
Although code could use many if-then-else's as in OP's code, it would be simple to convert the h:m:s time into seconds, subtract, and convert back to h:m:s. So I recommend a re-write:
typedef struct time {
int hours;
int minutes;
int seconds;
} time;
long time_sec(time t) {
return (t.hours * 60L + t.minutes)*60 + t.seconds;
}
time sec_time(long s) {
time t;
t.hours = s / 3600;
s %= 3600;
t.minutes = s / 60;
t.seconds = s %= 60;
return t;
}
time calculateTimeDiff(time time1, time time2) {
long t1 = time_sec(time1);
long t2 = time_sec(time2);
long diff = t1 - t2;
return sec_time(diff);
}
#include <stdio.h>
void test(time t1, time t2) {
printf("t1: %3d:%3d:%3d, ", t1.hours, t1. minutes, t1.seconds);
printf("t2: %3d:%3d:%3d, ", t2.hours, t2. minutes, t2.seconds);
time t3 = calculateTimeDiff(t1, t2);
printf("t1-t2: %3d:%3d:%3d, ", t3.hours, t3. minutes, t3.seconds);
t3 = calculateTimeDiff(t2, t1);
printf("t2-t1: %3d:%3d:%3d\n", t3.hours, t3. minutes, t3.seconds);
}
int main(void) {
test((time){14,00,00}, (time){13,00,00});
test((time){22,00,00}, (time){04,00,00});
}
Output
t1: 14: 0: 0, t2: 13: 0: 0, t1-t2: 1: 0: 0, t2-t1: -1: 0: 0
t1: 22: 0: 0, t2: 4: 0: 0, t1-t2: 18: 0: 0, t2-t1: -18: 0: 0
Note that the difference may result in negative values for the members of time returned in calculateTimeDiff().
You can change to time structure instead of both start and end time integer value
#include<iostream>
using namespace std;
void difftime(int startTime, int iRecordEndTime)
{
int duration_min = 0;
cout<<"iRecordEndTime = "<<iRecordEndTime<<endl;
cout<<"startTime = "<<startTime<<endl;
if ( (iRecordEndTime/100 < startTime/100) || ((iRecordEndTime/100 == startTime/100) && (iRecordEndTime%100 <= startTime%100)) )
{
duration_min = ((iRecordEndTime / 100 + 24)*60 + iRecordEndTime%100) - ((startTime/100)*60 + startTime%100);
}
else
{
duration_min = (iRecordEndTime / 100 - startTime/100)*60 + (iRecordEndTime%100 - startTime%100);
}
cout<<"duration_min = "<<duration_min<<endl;
}
int main()
{
cout<<"enter the start time Hour:Minutes xxxx"<<endl;
int startTime{0};
cin>>startTime;
cout<<"enter the End time Hour:Minutes xxxx"<<endl;
int iRecordEndTime{0};
cin>>iRecordEndTime;
difftime(startTime, iRecordEndTime );
}
Output
enter the start time Hour:Minutes xxxx\
2300\
enter the End time Hour:Minutes xxxx\
0000\
iRecordEndTime = 0\
startTime = 2300\
duration_min = 60

Calculate datetime difference in C

I need a function that can calculate the difference between two datetime (year, month, day, hours, minute, seconds). and then return the difference in the same format.
int main (){
struct datetime dt_from;
init_datetime(&dt_from, 1995, 9, 15, 10, 40, 15);
struct datetime dt_to;
init_datetime(&dt_to, 2004, 6, 15, 10, 40, 20);
struct datetime dt_res;
datetime_diff(&dt_from, &dt_to, &dt_res);
return 0;
}
void datetime_diff(struct datetime *dt_from, struct datetime *dt_to
, struct datetime *dt_res) {
//What can I do here to calculate the difference, and get it in the dt_res?
}
Please have a look and try this example which uses time.h and should be portable. It calculates the difference in days between the dates in your question. You can change the program a little so that it works the way you want.
#include <stdio.h>
#include <time.h>
#include <math.h>
int main() {
time_t start_daylight, start_standard, end_daylight, end_standard;;
struct tm start_date = {0};
struct tm end_date = {0};
double diff;
printf("Start date: ");
scanf("%d %d %d", &start_date.tm_mday, &start_date.tm_mon, &start_date.tm_year);
printf("End date: ");
scanf("%d %d %d", &end_date.tm_mday, &end_date.tm_mon, &end_date.tm_year);
/* first with standard time */
start_date.tm_isdst = 0;
end_date.tm_isdst = 0;
start_standard = mktime(&start_date);
end_standard = mktime(&end_date);
diff = difftime(end_standard, start_standard);
printf("%.0f days difference\n", round(diff / (60.0 * 60 * 24)));
/* now with daylight time */
start_date.tm_isdst = 1;
end_date.tm_isdst = 1;
start_daylight = mktime(&start_date);
end_daylight = mktime(&end_date);
diff = difftime(end_daylight, start_daylight);
printf("%.0f days difference\n", round(diff / (60.0 * 60 * 24)));
return 0;
}
Test
Start date: 15 9 1995
End date: 15 6 2004
3195 days difference
Or even simpler for non-interactive code and with standard or daylight savings time:
#include <stdio.h>
#include <time.h>
#include <math.h>
int main()
{
time_t start_daylight, start_standard, end_daylight, end_standard;;
struct tm start_date = {0};
struct tm end_date = {0};
double diff;
start_date.tm_year = 1995;
start_date.tm_mon = 9;
start_date.tm_mday = 15;
start_date.tm_hour = 10;
start_date.tm_min = 40;
start_date.tm_sec = 15;
end_date.tm_mday = 15;
end_date.tm_mon = 6;
end_date.tm_year = 2004;
end_date.tm_hour = 10;
end_date.tm_min = 40;
end_date.tm_sec = 20;
/* first with standard time */
start_date.tm_isdst = 0;
end_date.tm_isdst = 0;
start_standard = mktime(&start_date);
end_standard = mktime(&end_date);
diff = difftime(end_standard, start_standard);
printf("%.0f days difference\n", round(diff / (60.0 * 60 * 24)));
/* now with daylight time */
start_date.tm_isdst = 1;
end_date.tm_isdst = 1;
start_daylight = mktime(&start_date);
end_daylight = mktime(&end_date);
diff = difftime(end_daylight, start_daylight);
printf("%.0f days difference\n", round(diff / (60.0 * 60 * 24)));
return 0;
}
Here is the basic idea:
Convert your datetime into an integral type (preferable long long or unsigned long long) which represents your datetime value as it's smallest unit (second in your case). How to achieve that? Easy transform the single values into seconds and add everything together. (seconds + minutes * 60 + hours * 3600 ...)
Do this for both values and then subtract the integer values.
Now convert the single integer value, the time difference, back to a datetime. How? Start with the biggest unit (years) and divide the difference by the amount of seconds within one year (60 * 60 * 24 * 365). Now you know how many years are in between your two datetimes. Take the rest and divide it by the amount of seconds per month, and so on...
(Obviously I ignored everything rather complicated, like daylight saving time for example)
However I would highly recommend using struct tm from time.h as mentioned in the comments. It is portable and you can use difftime.

Elapsed Time C Program using struct

//import library
#include <stdio.h>
#include <stdlib.h>
//declare variable structure
struct time{
int hour;
int min;
int sec;
}startTime, endTime, different, elapsed;
//mould struct and compute elapsedTime
struct time elapsedTime(struct time start, struct time end){
int secondStart, secondEnd, secondDif;
secondEnd = end.hour * 60 * 60 + end.min * 60 + end.sec;
secondStart = start.hour * 60 * 60 + start.min * 60 + start.sec;
if (secondEnd>secondStart)
secondDif = secondEnd - secondStart;
else
secondDif = secondStart - secondEnd;
different.hour = secondDif / 60 / 60;
different.min = secondDif / 60;
return different;
}
//main function
void main(){
printf("Enter start time (Hour Minute Second) using 24 hours system : ");
scanf("%d %d %d", startTime.hour, startTime.min, startTime.sec);
printf("Enter end time (Hour Minute Second) using 24 hours system : ");
scanf("%d %d %d", endTime.hour, endTime.min, endTime.sec);
elapsed = elapsedTime(startTime, endTime);
}
Can someone help me check and run the code to check whether it is working or not?
You have a mistakes in main function, you should use in scanf int * instead of int so you must add &, you can see below:
//main function
void main(){
printf("Enter start time (Hour Minute Second) using 24 hours system : ");
scanf("%d %d %d", &startTime.hour, &startTime.min, &startTime.sec);
printf("Enter end time (Hour Minute Second) using 24 hours system : ");
scanf("%d %d %d", &endTime.hour, &endTime.min, &endTime.sec);
elapsed = elapsedTime(startTime, endTime);
}
I assume you would want to calculate different.sec so I think the correct calculation of the different time is:
secPerHr = 60 * 60;
secPerMin = 60;
if (secondDif >= secPerHr) {
different.hour = secondDif / secPerHr;
secondDif -= different.hour * secPerHr;
}
if (secondDif >= secPerMin) {
different.min = secondDif / secPerMin;
secondDif -= different.min * secPerMin;
}
different.sec = secondDif;
Also, for testing purposes you would probably want to display the result in your main function.

Find Difference Between Two Dates C

I am trying to take one date away from another in C and find the difference between them in days. However, this is much more complicated than it first appeared to me as I obviously have to allow for differing days in different years due to leap years and a differing numbers of days depending on which month it is. I did try to use time.h but I do not think that it allows for leap years.
Currently my data is stored as integers in an array, for example, {2010, 5, 1, 2011, 6, 1}.
So could someone please post or point me towards an algorithm that will help me achieve this task? Thank you very much.
The standard library C Time Library contains structures and functions you want.
This header file contains definitions of functions to get and
manipulate date and time information.
Also check C date and time functions and C program days between two dates
EDIT:-
Try this:
int main()
{
int day1,mon1,year1,day2,mon2,year2;
int ref,dd1,dd2,i;
clrscr();
printf("Enter first date day, month, year\n");
scanf("%d%d%d",&day1,&mon1,&year1);
printf("Enter second date day, month, year\n");
scanf("%d%d%d",&day2,&mon2,&year2);
ref = year1;
if(year2<year1)
ref = year2;
dd1=0;
dd1=dater(mon1);
for(i=ref;i<year1;i++)
{
if(i%4==0)
dd1+=1;
}
dd1=dd1+day1+(year1-ref)*365;
dd2=0;
for(i=ref;i<year2;i++)
{
if(i%4==0)
dd2+=1;
}
dd2=dater(mon2)+dd2+day2+((year2-ref)*365);
printf("\n\n Difference between the two dates is %d days",abs(dd2-dd1));
getch();
}
int dater(x)
{ int y=0;
switch(x)
{
case 1: y=0; break;
case 2: y=31; break;
case 3: y=59; break;
case 4: y=90; break;
case 5: y=120;break;
case 6: y=151; break;
case 7: y=181; break;
case 8: y=212; break;
case 9: y=243; break;
case 10:y=273; break;
case 11:y=304; break;
case 12:y=334; break;
default: printf("Invalid Input\n\n\n\n"); exit(1);
}
return(y);
}
or using time.h try like this:
#include <stdio.h>
#include <time.h>
int main ()
{
struct tm start_date;
struct tm end_date;
time_t start_time, end_time;
double seconds;
start_date.tm_hour = 0; start_date.tm_min = 0; start_date.tm_sec = 0;
start_date.tm_mon = 10; start_date.tm_mday = 15; start_date.tm_year = 113;
end_date.tm_hour = 0; end_date.tm_min = 0; end_date.tm_sec = 0;
end_date.tm_mon = 10; end_date.tm_mday = 20; end_date.tm_year = 113;
start_time = mktime(&start_date);
end_time = mktime(&end_date);
seconds = difftime(end_time, start_time);
printf ("%.f seconds difference\n", seconds);
return 0;
}
Algo:
Convert dates to struct tm.
Convert struct tm to time_t.
Take the difference between the time_ts. It yields the difference between dates in seconds.
Divide the difference in seconds by 86400 to convert it to days.
/* This function calculates the differance between two dates, passes 6 parameters date-month-year of first date and date-month-year of second date and prints the difference in date-weeks-year format */
void Date::subtract(int firstDate, int firstMonth, int firstYear,int secondDate, int secondMonth, int secondYear)
{
/*check the dates are valid or not */
if(isDateValid(firstDate,firstMonth,firstYear) && isDateValid(secondDate,secondMonth,secondYear) )
{
firstMonth = (firstMonth + 9) % 12;
firstYear = firstYear - firstMonth / 10;
FirstNoOfDays = 365 * firstYear + firstYear/4 - firstYear/100 + firstYear/400 + (firstMonth * 306 + 5) /10 + ( firstDate - 1 );
secondMonth = (secondMonth + 9) % 12;
secondYear = secondYear - secondMonth / 10;
SecondNoOfDays = 365 * secondYear + secondYear/4 - secondYear/100 + secondYear/400 + (secondMonth * 306 + 5) /10 + ( secondDate - 1 );
dayDifference = abs(FirstNoOfDays - SecondNoOfDays); /* uses absolute if the first date is smaller so it wont give negative number */
years = dayDifference / 365;
weeks = (dayDifference % 365)/7;
days = (dayDifference % 365) % 7;
cout<<years<<" years "<<weeks<<" weeks "<<days<< " days"<<endl;
}
else
{
cout<<"Invalid Date"<<endl;
}
}

Resources