11

现在我正在使用回历日期并尝试使用以下代码将它们转换为公历日期:

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/143330/12/143230/05/1433等等,所以如何处理该日期并将其转换为对应的公历

4

3 回答 3

9

这是现在在此代码上运行良好的代码我从函数返回日期作为字符串而不是作为datetime,但您可以简单地使用返回日期时间类型而不是字符串

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

呼叫回历

ltrCalValue.Text = ConvertDateCalendar(CalHijri.SelectedDate, "Hijri", "en-US");
于 2013-01-26T14:35:57.037 回答
0

一个月中一天的最大值可以通过以下方式计算DateTime.DaysInMonth(year, month)

并以这种方式使用它

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

int result = DateTime.DaysInMonth(2011, 2) // returns 28 being a non-leap year
于 2012-06-25T13:01:41.883 回答
-1

Hirji 的第 10 个月和第 12 个月没有第 30 天,因此该日期无效。

于 2012-06-25T13:07:22.960 回答