Behzad Shirani
Behzad Shirani

Reputation: 137

DateTime.Now returns wrong value in ASP.NET

DateTime.Now and DateTime.UtcNowreturns wrong value as you see in picture. even ToUniversalTime() function result the same value.

How can I use DateTime with ignoring local time zone?

DateTiem.Now returns local time

Upvotes: 1

Views: 1732

Answers (1)

Luaan
Luaan

Reputation: 63732

You're using a culture (looks like one of the Arabic cultures) that doesn't use the Gregorian calendar. If that's not what you want, you need to use a different culture.

If you want an invariant culture, use the invariant culture:

DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture)

This will produce the same string on every machine (provided the same DateTime value, of course) and can be parsed again with

DateTime.Parse("...", System.Globalization.CultureInfo.InvariantCulture)

If you don't want the formatting for persistence, just pick whatever culture works for what you're trying to do. Each culture has its own calendar, number formatting etc.

Just to make this clear, DateTime values do not have formats. The format comes from the ToString (which is called implicitly in the debugger and many other places like string.Format or <%= ... %>). ToString takes the current culture (per-thread) by default, so either change that (if it makes sense), or specify the desired culture explicitly when calling ToString (or string.Format etc.).

Upvotes: 1

Related Questions