.NET How to parse a Persian / Farsi date string (Jalali calendar) into a DateTime object?

Dan Bailiff picture Dan Bailiff · Apr 28, 2011 · Viewed 9.6k times · Source

I've run across several great code libraries for converting a Persian (Jalali calendar) date to a Gregorian date. However, my original source is a string, not a DateTime object. There doesn't seem to be official support in the .NET framework for parsing dates using the Persian calendar (if I'm wrong, please show me!).

My goal:

string persianDateString="1390/02/07";
DateTime persianDateTime = MyPersianParser.Parse(persianDateString, "yyyy/mm/dd");

And of course, some dates may use word names for months and days of the week, so I'd like to be able to support the standard format string protocol.

EDIT: I know about the typical DateTime.Parse functionality. The Persian calendar cannot be used because Microsoft left it incomplete and/or won't fix it. If anyone can point me to some Persian date parsing code I'd be grateful. If not, I'll request someone remove the question and just write it myself.

Answer

Arash Milani picture Arash Milani · Jul 27, 2011

You can always use the native System.Globalization.PersianCalendar .NET class. but it is a bit tricky.

Consider this code for converting from Jalali Date (here 1387/03/18) to Gregorian DateTime:

System.Globalization.PersianCalendar persianCal = new System.Globalization.PersianCalendar();
    DateTime GregorianDate = persianCal.ToDateTime(1387, 3, 18, 12, 0, 0, 0);

and the following code to convert a Gregorian DateTime (here 1983/08/03) to Persian Date string:

DateTime GregorianDate = DateTime.Parse("1983/08/03");
string FarsiDateConverted = persianCal.GetYear(GregorianDate).ToString("0000") + "/" +
             persianCal.GetMonth(GregorianDate).ToString("00") + "/" +
             persianCal.GetDayOfMonth(GregorianDate).ToString("00");

just a note for the link provided by @Dan Bailiff I should repeat the author of the article's words:

"The main purpose for using this JalaiCalendar in place of the .NET Framework's PersianCalendar must be the need of date conversation for historical events. If you just want to display the current date in your website, PersianCalendar is sufficient."

In fact algorithm of .NET Framework is correct for the years 1178 to 1634 Jalali (1799 to 2256 Gregorian)

Update:

Starting with the .NET Framework 4.6, the PersianCalendar class uses the Hijri solar astronomical algorithm rather than an observational algorithm to calculate dates. This makes the PersianCalendar implementation consistent with the Persian calendar in use in Iran and Afghanistan, the two countries in which the Persian calendar is in most widespread use. So if you use >4.6 version of .NET Framework you don't need any other libraries for converting dates to/from Persian Calendar.