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

心不动则不痛 提交于 2019-12-11 03:15:22

问题


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


回答1:


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.




回答2:


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.




回答3:


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();


来源:https://stackoverflow.com/questions/893689/how-to-render-local-time-given-utc-datetime-values-in-asp-net-without-using-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!