Convert from UTC Datetime to local datetime in view

So I inadvertently ran into the reality that Azure works with UTC time. This is normal, except that I only found it when it was deployed! (When it is in debug mode, it just uses my comps time, so this was missed)

Therefore, I need to be able to simply show the date and time to the user as is. I do not mind (and prefer) this at UTC. However, I have many different places that date from my application, so I wonder what a quick and dirty solution is to display all displays showing local time. I was thinking about using an editor template for datetime. Is that a good idea? What would I like to use for conversion?

+4
source share
2 answers

Here are the editor and display templates that allow the user to enter and display the time in their own time zone and convert it to UTC for sending.

For the UIHint attribute for the user value "UTCTime" for each UTC field DateTime of the model, as shown below, to select the correct display templates and editor. DateTimes on models without this annotation will not execute:

[UIHint("UTCTime")] [DataType(DataType.DateTime)] public DateTime LastSeen { get; set; } 

/Views/Shared/EditorTemplatesUTCTime.cshtml:

 @model DateTime? @{ var name = Html.GetFieldNameForModel(); // See the HTML extension at the end of this post var boxName = name + ".Value"; var boxId = name + "_Value"; var divId = name + "_UTC"; } @Html.TextBoxFor(m => m.Value, new { type = "datetime", onBlur ="$('#" + name + "').val(UTCDateFuncs.ToUTCDate($('#" + boxId + "').val()));$('#" + divId + "').html('UTC:' + $('#" + name + "').val());$('#" + boxId + "').attr('title','UTC:' + $('#" + name + "').val());" })<span id="@divId"></span> <script> new function () { var utcVal = $('#@(boxId)').val(); $('#@(boxId)').val(UTCDateFuncs.FromUTCDate(utcVal)); $('#@(boxId)').attr('title', 'converted from UTC ' + utcVal); } </script> @Html.HiddenFor(m=>m) 

\ Views \ Shared \ DisplayTemplates \ UTCTime.cshtml

 @model DateTime? @if(Model.HasValue){<span class="UTCTime">@Model</span>} 

Necessary javascript in the site template or somewhere (not in the template):

 // UTC Date $(function () { $('.UTCTime').each(function () { var oldtext = $(this).html(); var result = UTCDateFuncs.FromUTCDate(oldtext); $(this).html(result); $(this).attr("title", "Converted from UTC " + oldtext); }); }); var UTCDateFuncs = { ToUTCDate: function (datetext) { try { var n = new Date(datetext); offsetms = n.getTimezoneOffset() * 60 * 1000; n = new Date(n.valueOf() + offsetms); result = n.toDateString() + " " + n.toLocaleTimeString(); } catch (ex) { console.warn("Error converting time", ex); } return result; }, FromUTCDate: function (datetext) { var result; try { var n = new Date(datetext); offsetms = n.getTimezoneOffset() * 60 * 1000; n = new Date(n.valueOf() - offsetms); result = n.toDateString() + " " + n.toLocaleTimeString(); } catch (ex) { console.warn("Error converting time", ex); } return result; } }; 

Also utilizes this HTML extension: \ Controllers \ Extensions \ HtmlExtensions.cs

 using System; using System.Web.Mvc; public static class HtmlExtensions { public static string GetFieldNameForModel<TModel>(this HtmlHelper<TModel> htmlHelper) { var ti = htmlHelper.ViewData.TemplateInfo; var name = ti.HtmlFieldPrefix; return name; } } 

This is used exclusively on our administrative pages, therefore, after the text field, a not very convenient interface is displayed that shows the conversion result for the editor window.

+1
source

Did this help you?

The problem is that you do not know the time zone of the user on the server. You could at best guess one culture, but not a time zone. And an en-us culture can have at least 4 time zones if the user is in the USA.

Another approach would be for the user to select / select the preferred time zone when working with your site. You can then save this choice in a cookie or profile. Having a user’s time zone, you can convert between time zones in a method like this:

 var localDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, timeZone.TimeZoneInfo); 

Where do you use the static method ConvertTimeFromUtc TimeZoneInfo . And also you have an instance of TimeZoneInfo (in my case it is a property of my custom type) that stores the user TimeZoneInfo .

Returning to the jQuery solution - you can use this by calling this little function on document.ready (). You just have to keep in mind to add the desired css class to the time display fields.

But in the end, if you target visitors with multiple time zones, you can ask them for the preferred time zone to convert to the backend and explicitly display this time in UTC for users who did not select the selected TimeZone.

0
source

Source: https://habr.com/ru/post/1392810/


All Articles