c# - 是否可以在 .NET 中将非公历日期表示为 DateTime?

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

我在用 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/

相关文章:

c# - 通过引用?

java - 我有一个对象数组,每个对象都分配了一个日期,如何按日期顺序对这些对象进行排序?

c# - 一劳永逸什么是处理 MVC 中的错误、异常和 404 的最佳路由方法

c# - 嵌套三元运算符

c# - 不允许重载泛型类型参数?

php - Carbon 返回错误的日期错误

python - 如何在 python 中对 datetime.timedelta 执行除法?

c# - 尝试解析标记助手指令 '@addTagHelper' 时遇到意外错误

c# - 在 C# 中读取两个字符

c# - 使用 stub 和模拟的正确方法是什么?