Answer the question
In order to leave comments, you need to log in
What is the best way to work with timezones in web applications?
Hello!
Actually, a rather hackneyed question, but still I wanted to ask how you work with user time zones?
For myself, I still can’t choose from two scenarios:
1. Store the user’s timezone in the database, which he specified in the profile, then manipulate the times based on it.
2. Timezone (timezoneOffset - it doesn't matter) to determine on the client each time the web application is loaded, then write it to a cookie and transfer it to the server with each request.
* In the database, all times and dates are stored in UTC.
Or are there any more user and developer friendly methods?
Thank you.
Answer the question
In order to leave comments, you need to log in
Both methods have the right to life.
The 2nd is probably more convenient if the user can actively change the time zone.
At the same time, the 1st, in my opinion, is more stable and understandable to the user.
As a result, I chose the 2nd option, i.e. timezone stored in cookies.
Below I will present the implementation on ASP.Net Web Api (server) + JQuery (client)
Client (the jquery.cookie library was used ):
function setTimezoneCookie() {
var timezone_cookie = "tz";
// Инвертируем смещение (см. документацию к getTimezoneOffset)
var timezone_offset = (new Date().getTimezoneOffset())*(-1);
//Если нет - создаем
if (!$.cookie(timezone_cookie)) {
// проверка поддержки куков браузером
var isCookiesEnabled = 'isCookiesEnabled';
$.cookie(isCookiesEnabled, true);
if ($.cookie(isCookiesEnabled)) {
// удаляем тестовые куки
$.cookie(isCookiesEnabled, null);
// записываем timezone
$.cookie(timezone_cookie, timezone_offset);
}
}
else {
// Если куки с timezone уже есть, но отличается, то записываем новое значение
var storedOffset = parseInt($.cookie(timezone_cookie));
var currentOffset = timezone_offset;
if (storedOffset !== currentOffset) {
$.cookie(timezone_cookie, timezone_offset);
}
}
}
public class TimezoneHandler : DelegatingHandler
{
static public string TimezoneToken = "tz";
async protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
// Изначально, смещение относительно UTC нулевое
int timezoneOffset = 0;
// Получаем значение временной зоны из cookies
var cookie = request.Headers.GetCookies(TimezoneToken).FirstOrDefault();
if (cookie != null)
{
try
{
timezoneOffset = Int32.Parse(cookie[TimezoneToken].Value);
}
catch (FormatException)
{
// Ошибка в формате временного смещения - выставляем в нулевое
timezoneOffset = 0;
}
}
// Сохраняем временное смещение в свойствах HTTP-запроса
request.Properties[TimezoneToken] = timezoneOffset;
// Продолжаем выполнение HTTP-запроса
HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
return response;
}
}
public static void Register(HttpConfiguration config)
{
...
config.MessageHandlers.Add(new TimezoneHandler());
...
}
...
int? tzOffset = Request.Properties[TimezoneHandler.TimezoneToken] as int?;
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question