Cannot convert from Hijri Date to Gregorian date (C #)

Now I work with hijri dates and try to convert them to Gregorian dates using the following code:

string HijriDate; string[] allFormats ={"yyyy/MM/dd","yyyy/M/d", "dd/MM/yyyy","d/M/yyyy", "dd/M/yyyy","d/MM/yyyy","yyyy-MM-dd", "yyyy-Md","dd-MM-yyyy","dM-yyyy", "dd-M-yyyy","d-MM-yyyy","yyyy MM dd", "yyyy M d","dd MM yyyy","d M yyyy", "dd M yyyy","d MM yyyy","MM/dd/yyyy"}; CultureInfo enCul = new CultureInfo("en-US"); CultureInfo arCul = new CultureInfo("ar-SA"); arCul.DateTimeFormat.Calendar = new System.Globalization.HijriCalendar(); DateTime tempDate = DateTime.ParseExact(HijriDate, allFormats, arCul.DateTimeFormat, DateTimeStyles.AllowWhiteSpaces); return tempDate.ToString("MM/dd/yyyy"); 

this code works fine with all dates except for a date that has a 30th day in a month, as shown below:

'30 / 10/1433 ', '30 / 12/1432' or '30 / 05/1433 ', etc ... ... so how to process and convert this date with the corresponding Gregorian: S

+4
source share
3 answers

here is the code that it works well now in this code I return the date from the function as a string, not as a datetime, but you can just reuse the datetime type instead of a string

  public string ConvertDateCalendar(DateTime DateConv, string Calendar, string DateLangCulture) { System.Globalization.DateTimeFormatInfo DTFormat; DateLangCulture = DateLangCulture.ToLower(); /// We can't have the hijri date writen in English. We will get a runtime error - LAITH - 11/13/2005 1:01:45 PM - if (Calendar == "Hijri" && DateLangCulture.StartsWith("en-")) { DateLangCulture = "ar-sa"; } /// Set the date time format to the given culture - LAITH - 11/13/2005 1:04:22 PM - DTFormat = new System.Globalization.CultureInfo(DateLangCulture, false).DateTimeFormat; /// Set the calendar property of the date time format to the given calendar - LAITH - 11/13/2005 1:04:52 PM - switch (Calendar) { case "Hijri": DTFormat.Calendar = new System.Globalization.HijriCalendar(); break; case "Gregorian": DTFormat.Calendar = new System.Globalization.GregorianCalendar(); break; default: return ""; } /// We format the date structure to whatever we want - LAITH - 11/13/2005 1:05:39 PM - DTFormat.ShortDatePattern = "dd/MM/yyyy"; return (DateConv.Date.ToString("f", DTFormat)); } 

To call this method, here is an example

  ltrCalValue.Text = ConvertDateCalendar(CalHijri.SelectedDate, "Gregorian", "en-US"); 

to call hijri

  ltrCalValue.Text = ConvertDateCalendar(CalHijri.SelectedDate, "Hijri", "en-US"); 
+2
source

The maximum value of days in a month can be calculated DateTime.DaysInMonth(year, month)

and use it that way

 int result = DateTime.DaysInMonth(2012, 2); // returns 29 being a leap year 

but

 int result = DateTime.DaysInMonth(2011, 2) // returns 28 being a non-leap year 
0
source

The 10th and 12th months in Hirji do not have a 30th day, so the date is invalid.

-2
source

All Articles