Posts Tagged ‘HebrewCalendar’

Hebrew Extension methods

The .NET framework has great support for date globalization, and it’s very easy making conversion between the regular DateTime object and your specific one. Nonetheless, you still need to create your specific CultureInfo and set the specific calendar. Then, you should use the overloaded DateTime.ToString method with the cultureInfo and the format string, in order to get the desired result. If you intend to use one specific culture in your application, it could be very annoying writing this code every time.

A year ago, I had to write some code with an HebrewCalendar support. so I created an ExtendedDateTime class which handles all the date calculation for this calendar (Basically, all the cultured date classes are state-less, unlike the regular DateTime). But, after i saw Scott Mitchel great article about 5 Helpful DateTime Extension Methods, I thought it will be better providing extension methods for that propose. I’ll demonstrate here some, and the full source code will be available for download soon.

For all the DateTimeExtensions I’ll use the same culture object, like this:

static HebrewCalendar hebrewCalendar = new HebrewCalendar();
static CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("he-IL");

This 2 lines are not enough, and i also need to set the DateTimeFormat of the culture to the specific calendar I’ve just created. Because extension methods are part of a static class, I’ll use static constructor for doing this:

static DateTimeExtensions()
      cultureInfo.DateTimeFormat.Calendar = hebrewCalendar;

After creating those, writing the methods is simple, by using the built-in functions of the HebrewCalendar class. here are some examples:

public static string ToHebrewDateString(this System.DateTime date)
     return date.ToString("dd בMMMM, yyyy", cultureInfo);
public static bool IsLeapHebrewYear(this DateTime date)
     return hebrewCalendar.IsLeapYear(hebrewCalendar.GetYear(date));

Now, handling Hebrew dates is simple like handling basic dates:



I’ve also added some extension methods for Hebrew gematria (Integer and String objects), full source code will be available soon.

Categories: C# Tags: , ,
%d bloggers like this: