Saturday 25 October 2008

Gregorian, Julian or Korean?

To be an AWESOME Windows programmer you need to be able to manipulate calendars effortlessly, whether they be Gregorian, Julian or Korean. You should not need to rush to the nearest Internet access point to know the differences between Gregorian and Julian calendars.

Unfortunately the Calendar math of .NET is not so user-friendly especially when compared to recent additions to Python, for example.

Here is a small program that uses the Calendar class of Python 2.5 to generate dates for all weekends between 2000 and 2020. As you can see, the Calendar class is highly user-friendly (with its use of iterators) and also very ISO-friendly.

import sys
import datetime
from calendar import Calendar

def getdays(year):
c = Calendar(0) # creates a calendar with firstweek=0 (0 is Monday)
for j in range(1, 13):
for dt in c.itermonthdates(year, j):
isoweekday = dt.isoweekday()
if isoweekday == 6 or isoweekday == 7:
print dt.isoformat()

def main(args):
for year in range(2000, 2020):
days = getDays(year)

Beat that, .NET!

.NET possesess an eponymous Calendar class in its System.Globalization namespace (perhaps more appropriately named System.Localization, in the humble view of Windows Joe). In fact, .NET is so obsessed with Localization e.g. of date-time formats, that they completely ignore the fact that international ISO standards exist.

So the challenge - how do we program the same thing in C#? (Answer in the Comments section).

No comments: