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

标签 c# datetime calendar

我无法创建一个 DateTime 对象,该对象在 C# 中存储日期 02/29/101(台湾日期)而不更改 Thread 区域性。

当我这样做时:

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 值基本上始终在公历中。 (或者,或者您可以认为它们始终是“中性的”,但属性将值解释为公历。)台湾没有“A DateTime”这样的东西日历”- 您使用 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
    }
}

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

关于C# 创建一个代表台湾日期的 DateTime 对象 2 月 29 日 101(闰日),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9687212/

相关文章:

r - 将数字时间转换为 R 中的日期时间 POSIXct 格式

java - java.time 是否为 "yyyy-MM-dd"、 "HH:mm:ss"或类似变体等模式带来默认的 DateTimeFormatters ?

Java 日历无法正常工作

java - 使用 java 发送每封电子邮件的日历邀请

c# - 在构造函数中使用注入(inject)实现

c# - 自动sql表备份

c# - 使用动态条件读取文本文件

mysql - 使用 MySQL 查询模拟移动时间线

android - 使用来自 Web 的 Intent 打开 Android 日历 (Chrome)

c# - 在 WPF 中的两个窗口之间共享同一对象