所以我无意中遇到了 Azure 使用 UTC 时间的事实。这没关系,除了我只是在部署时才发现这一点! (当它处于 Debug模式时,它只使用我的比较时间,所以这被忽略了)
所以我需要能够向用户显示日期时间。我不介意(并且更喜欢)它是 UTC。 然而,我的应用程序中有很多不同的地方会弹出日期,所以我想知道什么是快速而肮脏的解决方案来让所有显示显示本地时间。我正在考虑使用日期时间编辑器模板。这是一个好主意吗?我将使用什么来进行转换?
最佳答案
以下是我提出的编辑器和显示模板,允许用户输入并显示自己时区的时间,并将其转换为 UTC 以便提交。
它需要将每个模型 UTC 日期时间字段的 UIHint 属性设置为自定义值“UTCTime”,如下所示,以选择正确的显示和编辑器模板。没有此注释的模型中的日期时间将不会受到影响:
[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>}
网站模板或某处(但不在模板中)所需的 javascript:
// 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;
}
};
还利用此 HTML 扩展: \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;
}
}
这仅在我们的管理页面上使用,因此在显示编辑器框转换结果的文本框后面有一个不太用户友好的范围。
关于javascript - 在 View 中从 UTC 日期时间转换为本地日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8995942/