- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我无法创建一个 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/
我是一名优秀的程序员,十分优秀!