Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Problem with dates! Please help. (http://www.go4expert.com/forums/dates-help-t23020/)

cyberbeast 16Aug2010 10:51

Problem with dates! Please help.
 
Hi all,

For a portion of my code, I need to either input a date from user or capture the system date. From there onwards I have to add 7 more days to the actual date and store it as the variable 'DueDate'. The format for the stored DueDate is DDMMYY. I am very confused as I am facing a lot of problems.

System time, seems very confusing and I cant get it to work, so I decided to stick to the traditional - "Let the user input the date" method.

Problems I need to tackle:
1. Output the DueDate in the correct format. Even if I meddle around with the input values as integers, I cant output in the correct format, for example - if the user enters "1" for month, I can not display it as "01" (and i need it to be 01 since that is the required format). How can i do that?

2. The logic I have applied for the date (like, incrementing month, if the due date exceeds number of days in month, or incrementing the year if month in duedate exceeds number of months in a year) is very troublesome.

Please help.

I wouldn't mind altering my code to use system time if it is less troublesome. I prefer neat coding in my programs.

Thank you.

xpi0t0s 17Aug2010 18:05

Re: Problem with dates! Please help.
 
You might find it's easier to manipulate dates as strings. However you can display 1 as 01 by displaying leading zeroes, e.g.
Code:

printf("%02d",1);
will print 01.

You will also need functions to convert dates to and from integers. This is by far the easiest way of doing date arithmetic, and you will probably need these functions anyway. Decide on a zero date - many programs use 01-Jan-1970 as zero, then any date can be stored as an offset in days from that date, e.g. 03-Jan-1970 would be 2, and 01-Jan-1971 would be 365. Or maybe you're prefer to use 01-Jan-2000 as zero; it doesn't really matter as long as you're consistent. Then if you want to add 7 to 27-dec-1999 it's a simple case of converting that to an int, adding 7, then converting back, and you won't need to mess about with carrying the excess days into the month, then the month into the year, which will get horrendously complicated when you have to take leap years into account.

With conversion functions your DueDate calculation for the above example could be as simple as
Code:

string DueDate=DateToStr(StrToDate("271299")+7);
making zillions of assumptions, but if you like neat coding then you probably can't get much neater than that.


All times are GMT +5.5. The time now is 16:22.