我在用 C# 将波斯语(回历)日期表示为 DateTime
时遇到问题,特别是在特定月份的某些日子,例如 31/04,在公历中这样的日期是无意义:
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
说:
年、月和日参数描述无法表示的日期时间。
这是预期的。
考虑到 30/02 和 31/04 等日期,我如何在 .NET 中将波斯语日期表示为 DateTime
?
最佳答案
The above code will result in an ArgumentOutOfRangeException saying: Year, Month, and Day parameters describe an un-representable DateTime.
是的,因为除非您指定日历,否则 DateTime
参数应该是公历。不过,您可以指定一个日历:
DateTime d1 = new DateTime(year, month, day, p);
请注意,如果您现在使用 d1.Year
,您将返回 2013,而不是 year
...DateTime
是 总是基本上是公历。但是,如果您使用将波斯日历作为默认日历的文化,那么当您将 DateTime
格式化为字符串时,它会适本地转换这些值。编辑:不幸的是,根据 documentation :
Currently, the PersianCalendar class is not an optional calendar for any culture supported by the CultureInfo class and consequently cannot be a default calendar.
正如评论中提到的Noda Time ,我可以解决这个问题:它还不支持波斯历。它支持农历回历,但不支持太阳历 :( 我可以考虑将其添加到 future 的版本中......
关于c# - 是否可以在 .NET 中将非公历日期表示为 DateTime?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17963646/