Skip to content

Instantly share code, notes, and snippets.

@lorddev
Created July 5, 2018 23:42
Show Gist options
  • Save lorddev/87a3a8111876145a9c6b4ddcab2d8d4e to your computer and use it in GitHub Desktop.
Save lorddev/87a3a8111876145a9c6b4ddcab2d8d4e to your computer and use it in GitHub Desktop.
JavaScript time localization for .NET MVC
// In JS:
// Base namespace
var app = app || {};
$.extend(true, app, {
localize: {
/**
* Local time; see http://blog.gauffin.org/2012/11/displaying-datetime-using-the-user-timezone-in-asp-net-mvc/
*/
init: function () {
$('[data-date]').each(function () {
// the date construct will automatically convert to local time
var localDate = new Date(parseInt($(this).data('date')));
if (localDate > 0) {
$(this).val(localDate.toLocaleDateString() + " " + localDate.toLocaleTimeString());
$(this).text(localDate.toLocaleDateString() + " " + localDate.toLocaleTimeString());
}
});
},
/**
* Returns the actual time in Greenwich, England when it was considered "today" (as in 0:00 AM)
* but in the user's time zone
*/
today: function (local) {
var d1 = new Date();
console.log(d1);
var y = d1.getFullYear();
var m = d1.getMonth();
var d = d1.getDate();
if (local) {
return new Date(y, m, d, 0, 0, 0, 0);
} else {
return new Date(Date.UTC(y, m, d, 0, 0, 0, 0));
}
}
}
});
$(function () {
app.localize.init();
});
// In static extensions class (C#)
public static class UnixTimeExtension
{
public static double GetMillisecondsSinceEpoch(this DateTime dateTime)
{
// Get the value in Unix time
var ms = dateTime.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds;
return ms;
}
}
// In Views/Shared/EditorTemplates/DateTime.cshtml
@using System.Globalization
@using GlassGo.Helpers
@model DateTime?
@{
// http://blog.gauffin.org/2012/11/displaying-datetime-using-the-user-timezone-in-asp-net-mvc/
var ms = 0D;
string dateString = null;
if (Model != null)
{
// Get the value in Unix time
ms = Model.Value.GetMillisecondsSinceEpoch();
dateString = Model.Value.ToString(CultureInfo.InvariantCulture);
}
}
<input type="text" id="@ViewData["id"]" name="@ViewData["id"]" data-date="@ms" value="@dateString" />
// In Views/Shared/DisplayTemplates/DateTime.cshtml
@using System.Globalization
@using GlassGo.Helpers
@model DateTime?
@{
// http://blog.gauffin.org/2012/11/displaying-datetime-using-the-user-timezone-in-asp-net-mvc/
var ms = 0D;
string dateString = null;
if (Model != null)
{
// Get the value in Unix time
ms = Model.Value.GetMillisecondsSinceEpoch();
dateString = Model.Value.ToString(CultureInfo.InvariantCulture);
}
}
<span data-date="@ms">@dateString</span>
// Example usage from a razor view:
<ul class="list-inline">
<li>From:</li>
<li>@Html.EditorFor(m => m.FromDateTime, new { id = "deFrom" })</li>
<li>to</li>
<li>@Html.EditorFor(m => m.ToDateTime, new { id = "deTo" })</li>
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment