是否可以在。net中將非公歷日期表示為DateTime ? - Is it possible to represent non gregorian dates as DateTime in .NET? -开发者知识库

是否可以在。net中將非公歷日期表示為DateTime ? - Is it possible to represent non gregorian dates as DateTime in .NET? -开发者知识库,第1张

I'm having trouble representing Persian (Solar Hijri Calendar) dates as DateTime in C#, specifically on certain days of particular months, for example 31/04 where in the Gregorian calendar such a date is meaningless:

我在用c#表示波斯歷(太陽希格里歷)日期時遇到了麻煩,特別是在特定月份的某些日子,例如在陽歷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);

The above code will result in an ArgumentOutOfRangeException saying: Year, Month, and Day parameters describe an un-representable DateTime.

上面的代碼將導致一個ArgumentOutOfRangeException:年、月和日參數描述一個不可表示的日期時間。

Which is expected.

這是預期。

How can I represent Persian Dates as DateTimes in .NET taking into accounts dates such as 30/02 and 31/04?

如何在。net中將波斯日期表示為日期時間,考慮到諸如30/02和31/04這樣的日期?

2 个解决方案

#1


3  

The above code will result in an ArgumentOutOfRangeException saying: Year, Month, and Day parameters describe an un-representable DateTime.

上面的代碼將導致一個ArgumentOutOfRangeException:年、月和日參數描述一個不可表示的日期時間。

Yes, because unless you specify a calendar, the DateTime arguments are expected to be Gregorian. You can specify a calendar though:

是的,因為除非您指定一個日歷,否則DateTime參數應該是Gregorian。你可以指定一個日歷:

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

Note that if you now take d1.Year, you'll get back 2013, not year... DateTime is always Gregorian, basically. However, if you use a culture which has the Persian calendar as the default calendar, that will convert the values appropriately when you format a DateTime into a string. EDIT: Unfortunately, as per the documentation:

注意,如果你現在取d1。你會回到2013年,而不是2013年……日期-時間基本上都是格里高里式的。但是,如果使用具有波斯歷作為默認日歷的文化,當您將DateTime格式化為字符串時,該文化將適當地轉換值。編輯:不幸的是,根據文件:

Currently, the PersianCalendar class is not an optional calendar for any culture supported by the CultureInfo class and consequently cannot be a default calendar.

目前,PersianCalendar類並不是CultureInfo類支持的任何文化的可選日歷,因此不能成為默認日歷。

As a comment has mentioned Noda Time, I can address that: it doesn't support the Persian calendar yet. It supports the lunar Hijri calendar, but not the solar one :( I could look into adding that into a future release...

正如我在評論中提到的野田佳彥時代,我可以這樣說:它還不支持波斯歷法。它支持的是“月海”歷,而不是太陽能日歷(我可以把它添加到未來的版本中……)

最佳答案:

DABAN RP主题是一个优秀的主题,极致后台体验,无插件,集成会员系统
U19学习网站 » 是否可以在。net中將非公歷日期表示為DateTime ? - Is it possible to represent non gregorian dates as DateTime in .NET? -开发者知识库