Friday, October 29, 2010

HebrewCalendar on Windows Phone 7 - Gotcha in leap years

Try converting a hebrew calendar date in Elul in a leap year using this code:


            DateTime myDateTime = new DateTime(1995, 9, 1);
            DateTime returnDateTime;
            HebrewCalendar hebrewCalendar = new HebrewCalendar();
            int jyear;
            int jmonth;
            int jday;
            jyear = hebrewCalendar.GetYear(myDateTime);
            jmonth = hebrewCalendar.GetMonth(myDateTime);
            jday = hebrewCalendar.GetDayOfMonth(myDateTime);
            returnDateTime = hebrewCalendar.ToDateTime(5767, jmonth, jday, 0, 0, 0, 0);

This will cause an error as 5767 is not a leap year and there are only 12 months in a non leap year, and jmonth is 13 in the code above.

(Elul is month 12 in non leap years and month 13 in leap years).

Solution
If the beginning year is a leap year and the end year is not a leap year
and the month index is greater than 7 //Adar II
then move the month back one


If the beginning year is not a leap year and the end year is a leap year

and the month index is greater than 7 //Adar II
then move the month forward one


            bool isLeap1 = hebCal.IsLeapYear(hYear);
            bool isLeap2 = hebCal.IsLeapYear(year);
           if ((isLeap1 & !isLeap2) & hMonth > 7)
            { hMonth--; }

           if ((!isLeap1 & isLeap2) & hMonth > 7)
           { hMonth++; }




Links:
http://www.hebcal.com/converter/?hd=11&hm=Elul&hy=5771&h2g=Convert+Hebrew+to+Gregorian+date
http://msdn.microsoft.com/en-us/library/system.globalization.hebrewcalendar(VS.95).aspx

This is a good right up with some examples on the HebrewDate class in C#.
http://www.ziporah-greve.net/prog/jewish-csharp.html


Side note:
This became much clearer to me when I had to create example code from my code.

No comments:

Post a Comment