Answer the question
In order to leave comments, you need to log in
How to take into account the user's timezone on an asp.net site?
Hello!
There is an old and big project on asp.net mvc. Hundreds of controllers and views used the @DateTime.Now construct to determine or display the current time on the page, which, of course, outputs the server's current time. Now I want to take into account the user's time zone (which is recorded in his profile).
I see a long and laborious path to this goal (which scares me with its size):
- in all places where I write the current date to the database, use DateTime.UtcNow
- in all places where I display the current date of the user, transfer it from world to local time
- all old dates in all database records should be converted from local time to world time
- the logic of services should be rewritten taking into account the time that is logical for it
in general, you will have to delve deeply into each line of code and, most likely, there will be errors %(
Maybe there are approaches that will make the task easier? for example, somehow overload the DateTime.Now method so that it returns world time or somehow set up the context ( session) of the user so that his local (other than the server) time is there.
Thank you for your attention and advice
Answer the question
In order to leave comments, you need to log in
DateTime.Now - just do a search and replace (by files). You can limit your search to file types ( .cs , .cshtml , .aspx , .ascx ) to keep things simple.
As for displaying the time in the desired time zone, it might be worth doing it using JavaScript . For each individual user, displaying time from the server side will be expensive (in terms of resource costs).
The first step is to make a helper method (or methods) that will accept the original date and time ( UTC or server time) and return the correct date and time.
In views, you can display dates and times at any time.span s, for example:
<p>
<span class="datetime">
@Html.GetDateTime(DateTime.Now)
</span>
</p>
<p>
<span class="datetime" data-timestamp="@Html.GetTimestamp()">
@Html.GetDateTime(DateTime.Now)
</span>
</p>
<p>Метод <b>Html.GetDateTime</b> вполне может возвращать дату в тегах, тогда будет:</p>
<p>@Html.GetDateTime(DateTime.Now)</p>
<p>а на выходе может быть:<p>
<p>
<span class="datetime" data-timestamp="123">
15.11.2016 21:11:21
</span>
</p>
<p>
<b>timestamp</b> - позволит обойти проблему с форматированием,
при расчете времени на стороне клиента.
</p>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question