c# - 无法从回历日期转换为公历日期 (c#)

标签 c# date 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 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 等,那么如何处理和转换它与其对应的公历日期

最佳答案

这是运行良好的代码 现在在这段代码中,我将从函数返回的日期作为字符串而不是 datetime,但是您可以简单地使用 return 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");

关于c# - 无法从回历日期转换为公历日期 (c#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11189807/

相关文章:

php - 选择两个日期之间的数据?

bash - 使用 sed 替换动态生成的字符串

excel - 回历日期格式

用于渲染 PDF 和 OCR 生成图像的 C# 解决方案?

c# - ServerManager CommitChanges 稍有延迟地进行更改

mysql - 加快临时表查询速度

angularjs - 如何在 angularjs Controller 中使用转换器对象的值

javascript - 将公历日期转换为回历日期

c# - wpf手动生成TreeViewItem容器

c# - MonoDevelop 3.1.1 找不到 System.Xml.Linq