2012-06-25 63 views
4

现在我用回历日期的工作,并试图将它们转换为使用下面的代码阳历日期转换:无法从回历日期公历日期(C#)

  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'等.....所以如何处理和将该日期转换为其相应的公历:S

回答

2

这里是现在运转良好 这个代码我是从功能字符串不是日期时间返回的日期代码,但你可以简单地使用reuturn 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"); 
0

一个月中某天的最大值可以通过DateTime.DaysInMonth(year, month)

,并使用这种方式在Hirji

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 
+0

是啊我的问题是,当你处理回教日期它不是像格里高利的几个月不变,因为它取决于新月所以也许第5个月是今年30天,但明年也许只有29天,所以问题通常将与第30天任何月份,这是我现在的问题:S –

+0

在这种情况下,您必须创建自己的函数,如'DateTime.DaysInMonth(year,month)',您将在其中发送年份和月份,并且它将返回该月份的日期。 –

-2

第10和第12个月没有30日做的,使日期是无效的。

+2

但是在所有月份发生的事情不仅仅是这两个月,所以如何处理呢? –