简体   繁体   中英

DateTime.Now/UtcNow Default Culture - Client or Server?

I know how to specify cultures, date formats, time zones, etc...

My question here is when you just type DateTime.Now or DateTime.UtcNow in C#, is it using the culture from the web server your server-side code runs on, or is it using the client-side lang/culture of the web browser making the request?

To my great surprise, from my testing, it looks like this server code DateTime.Now is not using the web server's culture. But is actually using the client Lang/Cult inside the web browser!?

Is there anyway in the web.config to specify DateTime.Now/UtcNow to run in my web server's culture by default? I only want client cultures to be applied when I write code specifically for them.

DateTime.Now and DateTime.UtcNow don't have any culture at all. It's only when you format one as a string that it will use a culture... and which culture is used will depend on how you format it. To be clear in your code, just specify the culture explicitly, eg

string text = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture);

However, DateTime.Now will use the system-local time zone (ie the one on the server). That's orthogonal to the culture used for formatting.

As Jon mentioned, DateTime.UtcNow (or any DateTime) does not have a culture -- it's essentially a UInt64 representation of a date, so it's just a number. When it's converted to a string for display (including by your debugger), that's when a culture would apply.

To address the question of how the browser culture settings could affect the culture settings on the server, is it possible that you have culture set to auto in the globalization section of your web.config or in a page directive ( http://msdn.microsoft.com/en-us/library/vstudio/bz9tc508(v=vs.100).aspx )?

To have ASP.NET set the UI culture and culture to the first language that is specified in the current browser settings, set UICulture and Culture to auto.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM