Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.Now.ToUniversalTime() Has the Wrong Year

And Idea Why the Year appears as 2555?

enter image description here

The culture of the site is Thai

like image 553
aron Avatar asked Dec 16 '12 17:12

aron


People also ask

How to define DateTime in C#?

C# includes DateTime struct to work with dates and times. To work with date and time in C#, create an object of the DateTime struct using the new keyword. The following creates a DateTime object with the default value. The default and the lowest value of a DateTime object is January 1, 0001 00:00:00 (midnight).

Is DateTime reference type in C#?

DateTime is a Value Type like int, double etc. so there is no way to assign a null value. When a type can be assigned null it is called nullable, that means the type has no value. All Reference Types are nullable by default, e.g. String, and all ValueTypes are not, e.g. Int32.

What is ToUniversalTime in C#?

The ToUniversalTime method converts a DateTime value from local time to UTC. To convert the time in a non-local time zone to UTC, use the TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo) method. To convert a time whose offset from UTC is known, use the ToUniversalTime method.

Should I use now or UtcNow?

When you need a local time for the machine your application runs at (like CEST for Europe), use Now. If you want a universal time - UtcNow.


1 Answers

Yes - any time DateTime is converted to a string with no explicit culture specified, it will use the current culture's calendar system. However, the DateTime components themselves still reflect the Gregorian calendar.

You'll see the 2555 if you use:

int thaiYear = new ThaiBuddhistCalendar().GetYear(DateTime.Now);

Basically, if you want to get culture-specific date information programmatically, you need to use a System.Globalization.Calendar. When formatting a date, make sure you specify the right culture for the calendar you want to use.

like image 91
Jon Skeet Avatar answered Sep 30 '22 15:09

Jon Skeet