問題描述
如何在不使用 Javascript 的情況下在 ASP.Net 中呈現給定 UTC 日期時間值的本地時間? (How to render local time given UTC datetime values in ASP.Net without using Javascript?)
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();
(by Max Schmeling、AnthonyWJones、JoshBerke、Kamarey)