// If Xmas falls later in the year (positive), convert from milliseconds to days,
// else convert to days and add 365 to get number of days until NEXT Christmas

if(diff >= 0)	
	daysToXmas=(((diff/1000)/60)/60)/24;
else
	daysToXmas=(365 + (((diff/1000)/60)/60)/24);

This section of code converts from milliseconds to days by making the appropriate conversions. There are 1000 milliseconds per second, 60 seconds per minute, etc. The division is kept in several small steps to keep the code understandable. Mathematically, it would have been equally correct to say,

daysToXmas = diff/86400000;

However, the code would not make much sense to anyone else looking at it (and possibly to yourself in a few months).

Because we performed a subtraction, we have to be aware of situations that will produce a negative number. In many cases a program will rely on negative numbers for their calculations, but in this example, it doesn't make sense to say,

There are -2 days until Christmas!

Because of this, it is necessary to calculate the number of days until the next Christmas. Adding 365 days and then subtracting diff will produce the correct value (one year from now and two days ago is Christmas, if you will excuse the incorrect grammar).

It should be noted that every four years, the program will be incorrect for six days, due to leap year. Although it's acceptable to fudge the calculations for this somewhat trivial example, imagine if your payroll program didn't pay you for a days worth of work every four years! On my salary, it might not be all that great a loss... but still.

Close window