C#创建一个DateTime对象,表示台湾日期2月29日101(闰日)

C#创建一个DateTime对象,表示台湾日期2月29日101(闰日),c#,datetime,calendar,C#,Datetime,Calendar,我不可能在不改变线程区域性的情况下创建一个DateTime对象,将日期02/29/101(台湾日期)存储在C#中 当我这样做时: DateTime date = new DateTime(2012, 2, 29, new TaiwanCalendar()); 它创建一个日期为1911年的DateTime对象。这个重载似乎是为了告诉DateTime对象您正在提供台湾日期,而不是您想要台湾日期 我能做到 DateTime leapDay = new DateTime(2012, 2, 29);

我不可能在不改变线程区域性的情况下创建一个DateTime对象,将日期02/29/101(台湾日期)存储在C#中

当我这样做时:

DateTime date = new DateTime(2012, 2, 29, new TaiwanCalendar());
它创建一个日期为1911年的DateTime对象。这个重载似乎是为了告诉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));
但这是一个字符串表示,我的调用代码需要返回一个DateTime对象,如下所示:

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

DateTime date = new DateTime(new TaiwanCalendar().GetYear(leapDay), new TaiwanCalendar().GetMonth(leapDay), new TaiwanCalendar().GetDayOfMonth(leapDay));
不起作用(我得到一个错误,说“年、月和日参数描述不可表示的日期时间”)

我需要一个DateTime对象,它可以准确地表示台湾日期,而不改变线程区域性。这项工作:

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

DateTime date = new DateTime(2012, 2, 29);
但是,一旦我将线程区域性更改回en-US,日期就会自动更改,这就阻止了我将其作为台湾日期返回


有什么方法可以做到这一点,或者我必须把日期作为字符串传递吗?

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
    }
}

<>编辑:正如XANATOS所指出的,你可能也想考虑一下。(我想说的是考虑改用,但我们还不支持此日历。当我们这样做时…

唯一要添加的是您可以编写
日历。ToDateTime(101,2,29,0,0,0,0,0,0)
(还有另一个重载,您可以指定
纪元
)这太糟糕了,我真的希望能够将任何有效的台湾日期存储到DateTime对象中,而无需更改我的区域性。听起来这是不可能的(我所知道的唯一一天是闰日)。谢谢您提供的信息。@omatase:不,您可以将其存储在
日期时间中
-只是它不“知道”这是一个台湾日期,您需要提供区域性以进行格式化。。。但这只是为了格式化的目的,对吗?对于任何计算,您只需直接使用calendar对象。
 var timeToConvert = DateTime.Now;  //whereever you're getting the time from
 var est = TimeZoneInfo.FindSystemTimeZoneById("Taipei Standard Time");
 return TimeZoneInfo.ConvertTime(timeToConvert, est).ToString("MM-dd-yyyy");