无法从Hijri日期转换为公历日期(c#)
现在,我正在使用Hijri日期,并尝试使用以下代码将其转换为公历日期:无法从Hijri日期转换为公历日期(c#),c#,date,hijri,C#,Date,Hijri,现在,我正在使用Hijri日期,并尝试使用以下代码将其转换为公历日期: 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-M-d","dd-MM-yyyy","d-M-yyyy", "dd-M-yyyy","d-MM-yyyy","yyyy MM d
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-M-d","dd-MM-yyyy","d-M-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");
此代码适用于除月份中有30天的日期以外的所有日期,如下所示:
30/10/1433
、30/12/1432
或30/05/1433
等。因此,如何处理和转换该日期及其相应的公历可以通过DateTime.DaysInMonth(年、月)
这样使用它
int result = DateTime.DaysInMonth(2012, 2); // returns 29 being a leap year
但是
Hirji中的第10个月和第12个月没有第30天,因此该日期无效。以下是代码,它运行良好 现在,在这段代码中,我将从函数返回日期作为字符串,而不是作为
datetime
,但是您可以简单地使用returndatetime类型来代替字符串
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));
}
下面是一个调用此方法的示例
ltrCalValue.Text = ConvertDateCalendar(CalHijri.SelectedDate, "Gregorian", "en-US");
叫Hijri
ltrCalValue.Text = ConvertDateCalendar(CalHijri.SelectedDate, "Hijri", "en-US");
但是所有的月份都会发生这种情况,不仅仅是这两个月,那么如何处理呢?是的,我的问题是,当你处理hijri日期时,它不像公历月份一样是恒定的,因为它取决于新月,所以今年的第五个月可能是30天,但明年可能只有29天,所以任何月份的问题通常都是30天这就是我现在的问题:在这种情况下,您必须创建自己的函数,如
DateTime.DaysInMonth(year,month)
在其中发送年和月,并返回该月的天。我得到:System.ArgumentOutOfRangeException:此日历中不支持指定的时间。该日期应介于07/18/0622 00:00:00(公历日期)和12/31/9999 23:59:59(公历日期)之间,包括在内。当我尝试上面的代码时。
ltrCalValue.Text = ConvertDateCalendar(CalHijri.SelectedDate, "Hijri", "en-US");