-
calendar program
I'm thinking about writing a calendar program for my own amusement, but I'm having some trouble thinking about storing the information. I can't imagine declaring an array up-front to store the entries (17,000+ for a single year). It seems like a waste of space. I've never considered this before. Does anyone have any ideas?
-
All you need is an algorithm to give you the day of the week that the first day of the month you are interested in falls on. When you know that the rest is easy. There are several algos that work.The one I use is Zellers algorithm. Search for that in a search engine. Check this sites source code pages for a calender example.
-
There's actually a linear function which will convert any day/month/year into a number... I'm not sure if this has a name...
Code:
void day2num (int month, int day, int year, int * num)
{
// Adjust calendar so that it is 0-indexed and starts at may.
month +=9;
month %= 12;
year -= month / 10;
// This is arbitrary. It just lets us handle year values back to -49,
year += 50;
// The formula.
*num = day + (month * 367 + 7) / 12 + year * (365 * 4 + 1) / 4;
return;
}
void num2day (int * month, int * day, int * year, int num)
{
*year = 4 * num / (365 * 4 + 1);
num -= *year * (365 * 4 + 1) / 4;
*month = (12 * num - 7) / 367;
num -= (*month * 367 + 7) / 12;
*day = num;
*year -= 50;
*year += *month / 10;
*month += 3;
*month %= 12;
return;
}
The function takes into acount leap years, but that's pretty much it, so it won't work over 100 year boundaries.
Addition and subtraction work to increment/decrement the days.. for example...
Code:
int main (void)
{
int m, d, y;
int n;
scanf ("%d %d %d", &m, &d, &y);
day2num (m, d, y, &n);
n += 50;
num2day (&m, &d, &y, n);
printf ("%d %d %d\n", m, d, y);
return 0;
}
Will take in a date, calculate the date that comes 50 days later, and display that date.
Incidentally... use at your own risk. :) I would like to think there isn't anything these functions are seriously lacking, but if there is, it's something that would only take a minor change. I wasn't able to find dates that mess this up.
-
I've created a calendar program once. basically, all you need to know is the current day, month, weekday and year and with those inputs, you can output the calendar month you want.