Ahad Porkar
Ahad Porkar

Reputation: 1698

C# calender conversion returns System.ArgumentOutOfRangeException

Im trying to convert GregorianCalendar into persian calender

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;
 }

problem is , its not working for all dates like this :

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

and it 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");

Upvotes: 6

Views: 1350

Answers (1)

rene
rene

Reputation: 42444

The argument exception is raised because you try to create a date that isn't valid in the Gregorian calendar.

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

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

you'll get 1394 4 31 and this is valid for a Persian calendar as in the remarks on MSDN it explains:

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 into a Gregorian calendar you'll have to run into trouble, because April doesn't have 31 days:

The Gregorian calendar has 12 months with 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" doesn't throw an exception because the results for the year, month and day are 1394 4 8 for the Persian calendar which are acceptable for the Gregorian calendar as well.

DateTime is considered to be a Gregorian calendar and to convert to a specific year, month or day in a calendar, call either GetYear, GetMonth or GetDayOfMonth of the calendar you're interested in, for example as shown here

Upvotes: 1

Related Questions