C # calendar conversion returns System.ArgumentOutOfRangeException

I am trying to convert a GregorianCalendar to a Persian calendar

this is my method:

public static DateTime GetFdate(string _Edate) { DateTime fdate = Convert.ToDateTime(_Edate); GregorianCalendar gcalendar = new GregorianCalendar(); PersianCalendar pcalendar = new PersianCalendar(); DateTime fDate = gcalendar.ToDateTime( pcalendar.GetYear(fdate), pcalendar.GetMonth(fdate), pcalendar.GetDayOfMonth(fdate), pcalendar.GetHour(fdate), pcalendar.GetMinute(fdate), pcalendar.GetSecond(fdate), 0); return fDate; } 

The problem is that it does not work for all dates:

 DateTime dt = GetFdate("2015-07-22 00:00:00.000"); 

and he gives this error:

 An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll Additional information: Year, Month, and Day parameters describe an un-representable DateTime. 

but for other dates it works, like this one:

 DateTime dt = GetFdate("2015-06-29 00:00:00.000"); 
+6
source share
1 answer

An argument exception occurs because you are trying to create a date that is not valid in the Gregorian calendar.

When you check the values ​​that you get from the Gregorian date "2015-07-22 00:00:00.000" for the Persian calendar

  pcalendar.GetYear(fdate).Dump(); pcalendar.GetMonth(fdate).Dump(); pcalendar.GetDayOfMonth(fdate).Dump(); 

you will get 1394 4 31, and this is true for the Persian calendar, as in the MSDN notes:

Each of the first six months in the Persian calendar has 31 days, each of the next five months has 30 days, and the last month has 29 days in a common year and 30 days in a leap year.

Obviously, when you feed this to the Gregorian calendar, you will have to face troubles because April does not have 31 days:

The Gregorian calendar has 12 months from 28 to 31 days each: January (31 days), February (28 or 29 days), March (31 days), April (30 days), May (31 days), June (30 days), July (31 days), August (31 days), September (30 days), October (31 days), November (30 days) and December (31 days).

the gregorian date "2015-06-29 00:00:00.000" does not throw an exception because the results for the year, month, and day are 1394 4 8 for the Persian calendar, which are also acceptable for the Gregorian calendar.

DateTime is considered the Gregorian calendar and is converted to a specific year, month or day on the calendar, calls either GetYear , GetMonth , or GetDayOfMonth the calendar you are interested in, for example, as shown here

+1
source

All Articles