I’m having an impossible time creating a DateTime object that stores the date 02/29/101 (Taiwan Date) in C# without changing the Thread culture.
When I do this:
DateTime date = new DateTime(2012, 2, 29, new TaiwanCalendar());
It creates a DateTime object with a date 1911 years in the future. It seems this overload is meant to tell the DateTime object that you’re providing a Taiwan date, not that you want a Taiwan date.
I can do this
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));
but that’s a string representation, and my calling code needs a DateTime object returned and this:
DateTime leapDay = new DateTime(2012, 2, 29);
DateTime date = new DateTime(new TaiwanCalendar().GetYear(leapDay), new TaiwanCalendar().GetMonth(leapDay), new TaiwanCalendar().GetDayOfMonth(leapDay));
doesn’t work (I get an error saying “Year, Month, and Day parameters describe an un-representable DateTime.”).
I need a DateTime object that can accurately represent a Taiwan date without changing the thread culture. This works:
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("zh-TW");
Thread.CurrentThread.CurrentCulture.DateTimeFormat.Calendar = new TaiwanCalendar();
DateTime date = new DateTime(2012, 2, 29);
but as soon as I change the thread culture back to en-US the date changes back automatically which prevents me from returning it as a Taiwan date.
Is there any way to do this, or am I going to have to pass my date around as a string?
DateTimevalues are always in the Gregorian calendar, basically. (Either that, or you can think of them as always being “neutral”, but the properties interpret the value as if it’s in the Gregorian calendar.) There’s no such thing as “ADateTimein a Taiwan calendar” – you use theTaiwanCalendarto interpret aDateTimein a particular way.If you need to format the
DateTimeusing a particular calendar, you can create the appropriateCultureInfoand pass that to theToStringmethod. For example:EDIT: As noted by xanatos, you might also want to consider
Calendar.ToDateTime. (I’d love to say think about using Noda Time instead, but we don’t support this calendar yet. When we do…)