是否可以在.NET中将非格里历日期表示为DateTime?

时间:2013-07-31 06:58:37

标签: c# .net datetime gregorian-calendar date-conversion

我无法在C#中将波斯语(Solar Hijri日历)日期表示为DateTime,特别是在特定月份的某些日子,例如31/04,在格里高利历中,这样的日期毫无意义:< / p>

System.Globalization.PersianCalendar p = new System.Globalization.PersianCalendar();
DateTime date = new DateTime(2013,7,22);
int year = p.GetYear(date);
int month = p.GetMonth(date);
int day = p.GetDayOfMonth(date);
DateTime d1 = new DateTime(year, month, day);

以上代码会导致ArgumentOutOfRangeException说: Year, Month, and Day parameters describe an un-representable DateTime.

预期。

我如何在.NET中DateTime代表波斯日期考虑日期,例如30/02和31/04?

2 个答案:

答案 0 :(得分:3)

  

以上代码将导致ArgumentOutOfRangeException:年,月和日参数描述不可表示的DateTime。

是的,因为除非您指定日历,否则DateTime参数应为Gregorian。您可以指定日历:

DateTime d1 = new DateTime(year, month, day, p);

请注意,如果你现在拿走d1.Year,你将会回到2013年,而不是year ... DateTime 总是格里高利,基本上。但是,如果您使用将波斯日历作为默认日历的文化,则在将DateTime格式化为字符串时,将适当地转换值。编辑:不幸的是,根据documentation

  

目前,PersianCalendar类不是CultureInfo类支持的任何文化的可选日历,因此不能是默认日历。

正如评论中提到Noda Time,我可以解决这个问题:它还不支持波斯日历。它支持月球Hijri日历,但不支持太阳能日历:(我可以考虑将其添加到未来版本中......

答案 1 :(得分:1)

来自 MSDN ;

  

每个DateTime成员都隐式使用公历来执行   它的操作,但指定了一个的构造函数除外   日历和带有从IFormatProvider派生的参数的方法,   比如System.Globalization.DateTimeFormatInfo,这是隐式的   指定日历。

同样来自 PersianCalendar Class

  

目前,PersianCalendar类不是可选的日历   CultureInfo类支持的任何文化,因此不能   是默认日历。

你想要的东西对我来说似乎不可能。