How to render local time given UTC datetime values in ASP.Net without using Javascript?

StackOverflow https://stackoverflow.com/questions/893689

  •  23-08-2019
  •  | 
  •  

Question

Is it possible to display local times to users without using Javascript when you store the values as UTC?

Was it helpful?

Solution

You would need serverside to be aware of the clients timezone. There isn't enough information in the typical request to make that determination, the closest you can get is the Accept_Language header which might give you a clue but is hardly useful enough (esp. if the client is in a country that has multiple timezones).

Hence you would need to user to tell you what their timezone is and then use a logon or cookie to store that info.

OTHER TIPS

You could do the conversion on the serverside in vb.net, c# or whatever .net language your using. You are going to have to convert to the local time somewhere.

Your asking a very broad question with no detail so I can't recommend how to do this on the server.

Edit

Based on the comments I see the problem your having is that you want to figure out what the users timezone is without javascript. I always have the user tell me their timezone when they register.

One approach which won't be perfect would be would to be use a geo-ip lookup service that will tell you most likely where your user and give your better granularity then using the language settings.

Think this is the closest you can do:

using System.Globalization;

// get the first language from request (en, fr, ru)
var primaryLanguage = Request.UserLanguages.First().Split(";").First();
// find a culture by this language
var culture = new CultureInfo(primaryLanguage);
// if the culture is neutral, try to find the specific one
if (culture.IsNeutralCulture)
    culture = CultureInfo.GetCultures(CultureTypes.SpecificCultures).FirstOrDefault(o => o.TwoLetterISOLanguageName == primaryLanguage);
// get the string from a datetime
var datetimeText = culture ? DateTime.Now.ToString(culture) : DateTime.Now.ToString();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top