2012-06-25 90 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

但是在所有月份發生的事情不僅僅是這兩個月,所以如何處理呢? –