簡體   English   中英

C#日歷轉換返回System.ArgumentOutOfRangeException

[英]C# calender conversion returns System.ArgumentOutOfRangeException

我試圖將GregorianCalendar轉換成波斯日歷

這是我的方法:

 public static DateTime GetFdate(string _Edate)
 {
      DateTime fdate = Convert.ToDateTime(_Edate);
      GregorianCalendar gcalendar = new GregorianCalendar();
      PersianCalendar pcalendar = new PersianCalendar();
      DateTime fDate = gcalendar.ToDateTime(
          pcalendar.GetYear(fdate),
          pcalendar.GetMonth(fdate),
          pcalendar.GetDayOfMonth(fdate),
          pcalendar.GetHour(fdate),
          pcalendar.GetMinute(fdate),
          pcalendar.GetSecond(fdate), 0);

      return fDate;
 }

問題是,它不適用於所有日期:

DateTime dt = GetFdate("2015-07-22 00:00:00.000");

它給出了這個錯誤:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll

Additional information: Year, Month, and Day parameters describe an un-representable DateTime.

但對於其他日期,它的工作原理如下:

DateTime dt = GetFdate("2015-06-29 00:00:00.000");

引發參數異常是因為您嘗試創建在公歷中無效的日期。

當您檢查從格里高利日期"2015-07-22 00:00:00.000"獲得波斯日歷的值時

 pcalendar.GetYear(fdate).Dump();
 pcalendar.GetMonth(fdate).Dump();
 pcalendar.GetDayOfMonth(fdate).Dump();

你會得到1394 4 31,這對於波斯日歷是有效的,就像在MSDN上的評論一樣,它解釋說:

波斯歷法的前六個月中的每一個都有31天,接下來的五個月中的每一個都有30天,而上個月在一個普通年份中有29天,在閏年中有30天。

很明顯,當你將它喂入格里高利歷時,你將不得不遇到麻煩,因為四月沒有31天:

公歷有12個月,每個28至31天:1月(31天),2月(28或29天),3月(31天),4月(30天),5月(31天),6月(30天) ,7月(31天),8月(31天),9月(30天),10月(31天),11月(30天)和12月(31天)。

格里高利日期"2015-06-29 00:00:00.000"不會引起例外,因為年歷,月份和日期的結果是波斯日歷的1394 4 8,這也是格里高利歷可以接受的。

DateTime被認為是公歷,要在日歷中轉換為特定的年,月或日,請調用您感興趣的日歷的GetYearGetMonthGetDayOfMonth ,例如此處所示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM