gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:06:30 27 4
gpt4 key购买 nike

我无法创建一个 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com