C# 如何解决波斯历法中的闰年问题

C# 如何解决波斯历法中的闰年问题,c#,datetime,leap-year,persian-calendar,C#,Datetime,Leap Year,Persian Calendar,今天是波斯历1397/02/29(yyyy/mm/dd)。 我的网站报告了他的错误: “年、月和日参数描述不可表示的日期时间。” 我在SQL数据库中使用了datetime2,并通过转换此日期在其中保存了波斯日期: PersianCalendar pc = new PersianCalendar(); DateTime dateTime = DateTime.Now; return new DateTime(pc.GetYear(dateTime), pc.GetMonth(dateTime),

今天是波斯历1397/02/29(yyyy/mm/dd)。 我的网站报告了他的错误:

“年、月和日参数描述不可表示的日期时间。”

我在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);

我该怎么办?

在这里我很无知。。。但一般来说,您应该使用普通日历(按照ISO 8601)处理“内部”(在程序和数据库中)所有日期,并且仅当您从用户读取输入/向用户写入输出时,才将其重新格式化为波斯语。在.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中,时间单位为100纳秒,在SQL中为1天)的数量,但随后它们处理日期的所有“标准”方法(在.NET和SQL中)使用公历(因为它是世界上使用最多的日历)。

使用此解决方案

static void Main(string[] args)
{
    Console.WriteLine(GetIsLeapDateTime(1358));
    Console.WriteLine(GetIsLeapDateTime(1359));
    Console.WriteLine(GetIsLeapDateTime(1360));
    Console.WriteLine(GetIsLeapDateTime(1361));
    Console.WriteLine(GetIsLeapDateTime(1362));
    Console.WriteLine(GetIsLeapDateTime(1363));
    Console.WriteLine(GetIsLeapDateTime(1364));
    Console.WriteLine(GetIsLeapDateTime(1365));
    Console.WriteLine(GetIsLeapDateTime(1366));
    Console.ReadLine();
}

private static bool GetIsLeapDateTime(int year)
{
    PersianCalendar pc = new PersianCalendar();
    return pc.IsLeapYear(year);
}
在贾拉里日历中

似乎每33年,闰年每5年发生一次,然后又回到每4年发生一次


1370年是闰年,但1374年不是闰年,而1375年是闰年。此外,1403年不是闰年,1407年不是闰年,而是1408闰年。

相关信息:hi@jahed这对1398不起作用,1399 1398不是闰年,1399是闰年,对于不熟悉波斯历法的人来说,是否有权威/任何著名的来源来检查一年是否是闰年?嗨@rezaakhlaghi,我检查了你的问题并更正了错误。感谢you@Pac0,是的,您可以使用“PersianCalendar”类中的“IsLeapYear”方法执行此操作