Question

I'm having trouble representing Persian (Solar Hijri Calendar) dates as DateTime in C#, specifically on certain days of particular months, for example 31/04 where in the Gregorian calendar such a date is meaningless:

System.Globalization.PersianCalendar p = new System.Globalization.PersianCalendar();
DateTime date = new DateTime(2013,7,22);
int year = p.GetYear(date);
int month = p.GetMonth(date);
int day = p.GetDayOfMonth(date);
DateTime d1 = new DateTime(year, month, day);

The above code will result in an ArgumentOutOfRangeException saying: Year, Month, and Day parameters describe an un-representable DateTime.

Which is expected.

How can I represent Persian Dates as DateTimes in .NET taking into accounts dates such as 30/02 and 31/04?

Was it helpful?

Solution

The above code will result in an ArgumentOutOfRangeException saying: Year, Month, and Day parameters describe an un-representable DateTime.

Yes, because unless you specify a calendar, the DateTime arguments are expected to be Gregorian. You can specify a calendar though:

DateTime d1 = new DateTime(year, month, day, p);

Note that if you now take d1.Year, you'll get back 2013, not year... DateTime is always Gregorian, basically. However, if you use a culture which has the Persian calendar as the default calendar, that will convert the values appropriately when you format a DateTime into a string. EDIT: Unfortunately, as per the documentation:

Currently, the PersianCalendar class is not an optional calendar for any culture supported by the CultureInfo class and consequently cannot be a default calendar.

As a comment has mentioned Noda Time, I can address that: it doesn't support the Persian calendar yet. It supports the lunar Hijri calendar, but not the solar one :( I could look into adding that into a future release...

OTHER TIPS

From MSDN;

Each DateTime member implicitly uses the Gregorian calendar to perform its operation, with the exception of constructors that specify a calendar, and methods with a parameter derived from IFormatProvider, such as System.Globalization.DateTimeFormatInfo, that implicitly specifies a calendar.

Also from PersianCalendar Class

Currently, the PersianCalendar class is not an optional calendar for any culture supported by the CultureInfo class and consequently cannot be a default calendar.

What you want seems not possible to me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top