c# - 如何解决波斯历中的闰年

标签 c# datetime leap-year persian-calendar

今天是波斯历 1397 年 2 月 29 日(年/月/日)。 我的网站报告了他的错误:

'Year, Month, and Day parameters describe an un-representable DateTime.'

我在 SQL 数据库中使用了 datetime2 并通过转换此日期将波斯日期保存在其中:

PersianCalendar pc = new PersianCalendar();
DateTime dateTime = DateTime.Now;
return new DateTime(pc.GetYear(dateTime), pc.GetMonth(dateTime), pc.GetDayOfMonth(dateTime), pc.GetHour(dateTime), pc.GetMinute(dateTime), pc.GetSecond(dateTime), 0);

我应该做什么?

最佳答案

这里相当无知......但一般来说,您应该使用正常的 Proleptic Gregorian “内部”(在程序和数据库中)处理所有日期。日历(根据 ISO 8601),并且仅当您从用户读取输入/向用户写入输出时将其重新格式化为波斯语。有一个PersianCalendar .NET 中的类可帮助将波斯语与美语相互转换。

例如

var pc = new PersianCalendar(); 
DateTime dt = pc.ToDateTime(1397, 02, 29, 0, 0, 0, 0); 

工作正常,但如果您查看 dt 变量,您会发现它显示为 2018-05-19。

如果对 DateTime 变量执行 ToString(),您会看到波斯日期,那么您的代码中可能存在错误。如果在数据库中的表上执行SELECT,您会看到波斯日期,那么您的数据库中可能有错误。

有趣的悖论是,.NET 和 SQL 在内部都将日期保存为单个数字,表示从日期的“零点”,但随后处理日期的所有“标准”方法(在 .NET 和 SQL 中)都使用公历(因为它是世界上使用最多的日历)。

关于c# - 如何解决波斯历中的闰年,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50423349/

相关文章:

c# - 一次移动两个 WPF 窗口?

C# - SMTP Gmail 在发送时挂起。第一次工作

PostgreSQL:如何测试时间戳是否有时区?

php - 反转 DateTime::createFromFormat/date_create_from_format 的函数

php - 增加一个月至今 2020-01-30 取消下个月

java - 检查闰年 - 不使用除法运算

c# - 如何在div中显示数据库值

c# - 不在 C# 中读取完整的串口数据

java - Swing 时间选择器

c# - 调用 ToUniversalTime().AddYears().ToLocalTime() 的闰年错误?