C#创建代表台湾日期的DateTime对象2月29日101(闰日)

oma*_*ase 2 c# datetime calendar

我有一个不可能的时间创建一个DateTime对象,在C#中存储日期02/29/101(台湾日期)而不更改线​​程文化.

当我这样做:

DateTime date = new DateTime(2012, 2, 29, new TaiwanCalendar());
Run Code Online (Sandbox Code Playgroud)

它创建一个DateTime对象,其日期为1911年.看来这个重载是为了告诉DateTime对象你提供了一个台湾日期,而不是你想要一个台湾日期.

我可以做这个

DateTime leapDay = new DateTime(2012, 2, 29);

string date = string.Format("{0}/{1}/{2}", new TaiwanCalendar().GetYear(leapDay), new TaiwanCalendar().GetMonth(leapDay), new TaiwanCalendar().GetDayOfMonth(leapDay));
Run Code Online (Sandbox Code Playgroud)

但这是一个字符串表示,我的调用代码需要返回一个DateTime对象,这个:

DateTime leapDay = new DateTime(2012, 2, 29);

DateTime date = new DateTime(new TaiwanCalendar().GetYear(leapDay), new TaiwanCalendar().GetMonth(leapDay), new TaiwanCalendar().GetDayOfMonth(leapDay));
Run Code Online (Sandbox Code Playgroud)

不起作用(我得到一个错误说"年,月和日参数描述了一个不可表示的DateTime.").

我需要一个可以准确表示台湾日期而不改变线程文化的DateTime对象.这有效:

Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("zh-TW");
Thread.CurrentThread.CurrentCulture.DateTimeFormat.Calendar = new TaiwanCalendar();

DateTime date = new DateTime(2012, 2, 29);
Run Code Online (Sandbox Code Playgroud)

但是一旦我将线程文化更改回en-US,日期会自动更改,这会阻止我将其作为台湾日期返回.

有没有办法做到这一点,或者我将不得不把我的约会作为字符串传递?

Jon*_*eet 7

DateTime总是在公历,基本上是这样.(要么就是这样,或者你可以认为它们总是处于"中立"状态,但是属性将这个值解释为格里高利历中的那个.)没有" DateTime台湾日历中的A"这样的东西- 你用它TaiwanCalendar解释一个DateTime以特定的方式.

如果您需要格式化DateTime使用特定的日历,您可以创建适当的CultureInfo,并传递给ToString方法.例如:

using System;
using System.Globalization;

class Test
{
    static void Main()        
    {
        var calendar = new TaiwanCalendar();
        var date = new DateTime(101, 2, 29, calendar);
        var culture = CultureInfo.CreateSpecificCulture("zh-TW");
        culture.DateTimeFormat.Calendar = calendar;       

        Console.WriteLine(date.Year); // 2012
        Console.WriteLine(date.ToString(culture)); // 101/2/29 [etc]
        Console.WriteLine(date.ToString("d", culture)); // 101/2/29
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:正如xanatos所述,您可能还需要考虑Calendar.ToDateTime.(我想说要考虑使用Noda Time,但我们还不支持这个日历.当我们这样做时...)