| | |
Problem calculating days between 2 dates
![]() |
•
•
Join Date: Apr 2009
Posts: 20
Reputation:
Solved Threads: 1
Hi everyone!
I'm trying to learn C from my dad's old college textbooks, and I'm doing some of the problems he had to do. This problem is meant to calculate the number of days between two dates given by the user. I made a function to account for leap years, and to input the data. My program is running, but is coming up with numbers that are just a few days off. I already wrote this program in Pascal, and it works, but I'm trying to practice it in C.
Here's the source code.
Thanks for the help!
I'm trying to learn C from my dad's old college textbooks, and I'm doing some of the problems he had to do. This problem is meant to calculate the number of days between two dates given by the user. I made a function to account for leap years, and to input the data. My program is running, but is coming up with numbers that are just a few days off. I already wrote this program in Pascal, and it works, but I'm trying to practice it in C.
Here's the source code.
C Syntax (Toggle Plain Text)
/*This program counts the days between two dates input by the user*/ #include <stdio.h> int yr1; /*global variables because all these need to be visible by multiple functions*/ int yr2; /*I don't know how to use pointers to return more than 1 variable from a function*/ int m1; int m2; int d1; int d2; int leap; main() { int numdays [13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; /*13 members*/ int totaldays; /*so that 1 would match up with January, fixing notation problems*/ int year; int month; int day; inputdata(); for (year = (yr1 + 1); year < yr2; year ++) /*processes complete years*/ { leapyr(year); if (leap == 1) totaldays += 366; else totaldays += 365; } year = yr1; for(month = m1 + 1; month <= 12; month++) /*processes incomplete year 1*/ { leapyr (year); if (leap == 1) numdays[2] = 29; else numdays[2] = 28; totaldays = totaldays + numdays[month]; } month = m1; for(day = d1; day <= numdays [month]; day++) /*processes incomplete month 1*/ { leapyr (year); if (leap == 1) numdays[2] = 29; totaldays += 1; } year = yr2; for(month = m2 - 1; month >= 1; month--) /*processes incomplete year 2*/ { leapyr (year); if (leap == 1) numdays[2] = 29; totaldays += numdays[month]; } month = m2; for(day = d2; day > 1; --day) /*processes incomplete month 2*/ { totaldays += 1; /*no need for leapyr function here- don't need to know month max*/ } printf("Total number of days between two given dates is: %d days", totaldays); getch(); } int inputdata() /*function works as planned- already tested*/ { printf("This program calculates the number of days between two given dates\n"); printf("Enter beginning date in form month/day/year: "); scanf( "%d/%d/%d", &m1, &d1, &yr1); printf("Enter ending date in form month/day/year: "); scanf("%d/%d/%d", &m2, &d2, &yr2); } int leapyr (year) { int leap = 0; if (year % 4 == 0) leap = 1; else if (year % 100 == 0) leap = 0; else if (year % 400 == 0) leap = 1; printf("leap is: %d\n", leap); return leap; }
Thanks for the help!
Last edited by patrick k; Jun 19th, 2009 at 12:54 pm.
here's one problem that immediately jumps out:
you need to assign the variable leap to the return value of the function
but, more importantly, you should really consider using the standard C library <time.h>
pay attention to the time_t and tm structures. it will reduce your code to a few lines to accomplish the same thing.
.
c Syntax (Toggle Plain Text)
leapyr (year); if (leap == 1)
you need to assign the variable leap to the return value of the function
c Syntax (Toggle Plain Text)
leap = leapyr(year)
but, more importantly, you should really consider using the standard C library <time.h>
pay attention to the time_t and tm structures. it will reduce your code to a few lines to accomplish the same thing.
.
Last edited by jephthah; Jun 19th, 2009 at 1:11 pm.
IMO the easiest way is to convert both date strings into time_t integers, then just subtract the two integers. That will give you the difference in seconds. After that its just dividing up the seconds into minutes, hours, and days.
The instructions say nothing about calculating the number of years between two dates. so leap years are not relevant to the problem.
The instructions say nothing about calculating the number of years between two dates. so leap years are not relevant to the problem.
C Syntax (Toggle Plain Text)
#include <time.h> #include <stdio.h> #include <stdlib.h> time_t tokenizedate(const char* datestr) { struct tm tm; memset(&tm,0,sizeof(struct tm)); tm.tm_mday = ((datestr[0] - '0') * 10) + (datestr[1] - '0'); tm.tm_mon = ((datestr[2] - '0') * 10) + (datestr[3] - '0') - 1; tm.tm_year = atoi(&datestr[4]) - 1900; return mktime(&tm); } int main() { time_t t1, t2; char date1[40], date2[40]; time_t seconds = 0, minutes = 0, hours = 0, days = 0, months = 0; printf("Enter first date (DDMMYYYY format)\n"); fgets(date1, sizeof(date1), stdin); printf("Enter second date (DDMMYYYY format)\n"); fgets(date2, sizeof(date2), stdin); t1 = tokenizedate(date1); t2 = tokenizedate(date2); seconds = t2 - t1; minutes = seconds / 60; hours = seconds /(60 * 60); days = seconds / (60 * 60 * 24); }
Last edited by Ancient Dragon; Jun 19th, 2009 at 1:22 pm.
•
•
Join Date: Apr 2009
Posts: 20
Reputation:
Solved Threads: 1
I've never dealt with the library functions in this program... I've only been programming in C for a couple days actually... So how can I figure out the functions in the library? Right now some of this is just gibberish to me.... Maybe it's just because I haven't had much experience yet though.
Last edited by patrick k; Jun 19th, 2009 at 1:40 pm.
ahhh... i see what you're trying to do.... i wasnt really paying attention ... and no, what you're doing is not quite right.
think of this:
whatever the function *returns* is assigned via the assignment operator, in this case to the variable "returnValue".
the variable you pass in to the function, the "argument" can either be an input or an output or both.
in your case,
your function "leapyr" gets this undefined "leap" value and throws it around and changes it to something meaningful, then tries to *return* it back to the calling function (main), who ignores it, since the return value is unassigned.
meanwhile, "main" still has the original, locally-scoped variable "leap" which is still unknown, and anything that the "leapyr" function did to it was just temporary within the "leapyr" function, and so is lost on "leapyr"'s memory stack.
so, the easiest fix is to redefine your function, leapyr, to look like this:
and when you call leapyr, call it like so
it's very important that you understand this concept: the variable "leap" that you declared (but did not define) that is local to the "main()" function, will NOT be the same variable as "leap" defined local to the "leapyr" function. they will be two totally independent and completely unrelated variables, just like a guy named "Joe Smith" in New York is unrelated to some other "Joe Smith" in Los Angeles.
the only way they are connected, is that the numeric *VALUE* that the one contains is *RETURNED* through the function and that value is assigned to the other. the variables may as well have two different names, there would be no difference.
think of this:
C Syntax (Toggle Plain Text)
returnValue = myFunction(argument);
whatever the function *returns* is assigned via the assignment operator, in this case to the variable "returnValue".
the variable you pass in to the function, the "argument" can either be an input or an output or both.
in your case,
leapyr(leap); you are passing the *value* of the argument, which in your example is "leap". leap, in your case is strictly undefined in the "main" routine, you have not given it a value. it may be zero, it may be negative eleventy-thousand, you dont know. your function "leapyr" gets this undefined "leap" value and throws it around and changes it to something meaningful, then tries to *return* it back to the calling function (main), who ignores it, since the return value is unassigned.
meanwhile, "main" still has the original, locally-scoped variable "leap" which is still unknown, and anything that the "leapyr" function did to it was just temporary within the "leapyr" function, and so is lost on "leapyr"'s memory stack.
so, the easiest fix is to redefine your function, leapyr, to look like this:
c Syntax (Toggle Plain Text)
int leapyr(void) { int leap; // locally defined, not the same variable in "main" // do your stuff return leap; }
and when you call leapyr, call it like so
C Syntax (Toggle Plain Text)
leap = leapyr();
it's very important that you understand this concept: the variable "leap" that you declared (but did not define) that is local to the "main()" function, will NOT be the same variable as "leap" defined local to the "leapyr" function. they will be two totally independent and completely unrelated variables, just like a guy named "Joe Smith" in New York is unrelated to some other "Joe Smith" in Los Angeles.
the only way they are connected, is that the numeric *VALUE* that the one contains is *RETURNED* through the function and that value is assigned to the other. the variables may as well have two different names, there would be no difference.
Last edited by jephthah; Jun 19th, 2009 at 1:46 pm.
•
•
Join Date: Apr 2009
Posts: 20
Reputation:
Solved Threads: 1
I understand that declaring leap in the main function and in the leapyr function are different, but that's why I declared leap globally, which I know is bad practice, but I did it anyway. I thought that made leap visible to all functions, and thus any changes applied by one function could be seen by other functions. Is this in concept wrong?
•
•
•
•
I've never dealt with the library functions in this program... I've only been programming in C for a couple days actually... So how can I figure out the functions in the library? Right now some of this is just gibberish to me.... Maybe it's just because I haven't had much experience yet though.

library functions are very powerful. essentially, they're just routines someone else has written to do some operation that is commonly used.
like "printf" is a library function (found in the <stdio.h> library) to print stuff to the terminal. <time.h> is another such library. learn the rules to use the functions in that library and life gets much easier.
look at Ancient Dragon's example above. it's probably a bit complex to you right now, but its easy to understand if you spend some time on it.
teh best way to learn is to use a debugger and "step through" the code one line at a time and watch the variables as they change values.
![]() |
Similar Threads
- Need Help Calculating Days Active based on dates (Visual Basic 4 / 5 / 6)
- calculating the difference between 2 dates (Visual Basic 4 / 5 / 6)
- how to calculate the days between two dates excluding saturday and sunday (JavaScript / DHTML / AJAX)
- Calculate working days between dates (PHP)
- problem calculating cost (C++)
- array structs, size swap functions, the amount of days between to dates (C++)
- help calculating days (C++)
Other Threads in the C Forum
- Previous Thread: 13th friday in c
- Next Thread: How to swap rows in single diemensional array
| Thread Tools | Search this Thread |
* adobe api array arrays binarysearch calculate centimeter char cm convert copyanyfile copypdffile cprogramme createcopyoffile createprocess() csyntax directory dynamic feet fflush file floatingpointvalidation fork forloop frequency getlasterror getlogicaldrivestrin givemetehcodez global graphics gtkgcurlcompiling gtkwinlinux hacking hardware highest homework i/o ide inches incrementoperators intmain() iso km linked linkedlist linux linuxsegmentationfault list locate logical_drives loopinsideloop. match matrix microsoft motherboard mqqueue mysql oddnumber odf open opendocumentformat opensource openwebfoundation pattern pdf performance pointer posix power program programming pyramidusingturboccodes read recursion recv recvblocked repetition scanf scheduling segmentationfault send shape single socketprograming socketprogramming stack standard strchr string suggestions test unix urboc user variable voidmain() whythiscodecausesegmentationfault win32api windows.h






