asp.net-mvc MVC - UTC 日期到 LocalTime
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5958662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC - UTC date to LocalTime
提问by Amitesh
We have a MVC project and I need to display a UTC date converted to users local time. In my model I am passing the UTC date and in the view I am trying to do the following:
我们有一个 MVC 项目,我需要显示一个转换为用户本地时间的 UTC 日期。在我的模型中,我正在传递 UTC 日期,并且在视图中我尝试执行以下操作:
<%: Html.DisplayFor(m=> m.SomeDate.ToLocalTime()) %>
This throws an exception. Can anybody point me in the correct direction on how to convert the UTC date to local datetime for display at customer end. We will be storing dates as UTC and at display time these dates will need to be converted to the local machine equivalent.
这会引发异常。任何人都可以指出我如何将 UTC 日期转换为本地日期时间以在客户端显示的正确方向。我们将日期存储为 UTC,并且在显示时间这些日期需要转换为本地机器等价物。
回答by Chad Moran
DateTime now = DateTime.UtcNow;
DateTime localNow = TimeZoneInfo.ConvertTimeFromUtc(now, TimeZoneInfo.Local);
回答by Trent Scholl
You will need to store the users timezone server side and then use something like this (although it should be done in the controller, not the view):
您将需要存储用户时区服务器端,然后使用这样的东西(虽然它应该在控制器中完成,而不是在视图中):
@TimeZoneInfo.ConvertTimeFromUtc(Model.CreatedOn, TimeZoneInfo.FindSystemTimeZoneById("E. Australia Standard Time"))
回答by Jignesh Variya
In mvc you can solve this issue by action filter.
Please use the following steps:
1) Store client timezone offset info in session.
2) Create DatetimeConverter helper class.
在 mvc 中,您可以通过操作过滤器解决此问题。请使用以下步骤:
1) 在会话中存储客户端时区偏移信息。
2) 创建 DatetimeConverter 助手类。
public class DateTimeConverter
{
public static DateTime? ToLocalDatetime(DateTime? serverDate, int offset)
{
if (serverDate == null) return null;
return serverDate.Value.AddMinutes(offset * -1);
}
}
3).Create action filter.
3).创建动作过滤器。
public class LocalDateTimeConverter : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var model = filterContext.Controller.ViewData.Model;
if (model != null && filterContext.HttpContext.Session["LocalTimeZoneOffset"] != null)
ProcessDateTimeProperties(model, filterContext);
base.OnActionExecuted(filterContext);
}
private void ProcessDateTimeProperties(object obj, ActionExecutedContext filterContext)
{
if (obj.GetType().IsGenericType)
{
foreach (var item in (IList)obj)
{
ProcessDateTimeProperties(item, filterContext);
}
}
else
{
TypeAccessor member;
List<PropertyInfo> props = new List<PropertyInfo>();
props.AddRange(obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty).ToList());
member = TypeAccessor.Create(obj.GetType());
foreach (PropertyInfo propertyInfo in props)
{
if (propertyInfo.PropertyType == typeof(DateTime) || propertyInfo.PropertyType == typeof(DateTime?))
{
{
member[obj, propertyInfo.Name] = DateTimeConverter.ToLocalDatetime((DateTime?)propertyInfo.GetValue(obj), ((int)filterContext.HttpContext.Session["LocalTimeZoneOffset"]));
}
}
else if (propertyInfo.PropertyType.IsGenericType && propertyInfo.GetValue(obj) != null)
{
foreach (var item in (IList)propertyInfo.GetValue(obj))
{
ProcessDateTimeProperties(item, filterContext);
}
}
}
}
}
}
4).Apply LocalDateTimeConverter filter on action which contains model data to return view.
4).对包含模型数据的操作应用LocalDateTimeConverter过滤器以返回视图。
After these all step you can see the result in view which contains dateTime info converted into local dateTime.
在所有这些步骤之后,您可以在视图中看到结果,其中包含转换为本地日期时间的日期时间信息。
回答by Mike S
You can't do ToLocalTime() on the server since the server is in UTC. You either need to:
您不能在服务器上执行 ToLocalTime() ,因为服务器采用 UTC。您要么需要:
- Have the client somehow send up it's timezone (this can be tricky since you won't get it by default with a GET request)
- Have the server send down UTC and the client converts it to the local time. This happens naturally if you're using AJAX, but is cumbersome with just a razor view:
- 让客户端以某种方式发送它的时区(这可能很棘手,因为默认情况下您不会通过 GET 请求获取它)
- 让服务器向下发送 UTC,客户端将其转换为本地时间。如果您使用 AJAX,这会自然发生,但仅使用剃刀视图就很麻烦:
Here's a trick I used for to make the 2nd approach very easy for Razor views:
这是我用来使 Razor 视图的第二种方法非常容易的技巧:
The server renders elements with a special class ".mytime" and the utc time (from server) specified in a custom attribute "utc":
服务器呈现具有特殊类“.mytime”和自定义属性“utc”中指定的 utc 时间(来自服务器)的元素:
<div class="mytime" utc ="@date.ToString("o")"></div>
<span class="mytime" utc ="2018-12-28T02:36:13.6774675Z"></span>
Note that .ToString("o") is how to write in UTC time.
请注意, .ToString("o") 是如何以 UTC 时间写入的。
And then have a local jQuery function iterate through all the elements with "mytime" class, read the UTC value in the attribute, and then do the conversion.
然后让本地 jQuery 函数遍历所有具有“mytime”类的元素,读取属性中的 UTC 值,然后进行转换。
$(function () {
var key = $(".mytime").each(function (i, obj) {
var element = $(this); // <div> or <span> element.
var utc = element.attr("utc"); // "2018-12-28T02:36:13.6774675Z"
var d = new Date(utc);
var l = d.toLocaleString(); // Runs client side, so will be client's local time!
element.text(l);
});
});
I then created a MVC razor helper for rendering:
然后我创建了一个用于渲染的 MVC razor helper:
public static MvcHtmlString LocalDate(this HtmlHelper helper, DateTime date)
{
// Must use MvcHtmlString to avoid encoding.
return new MvcHtmlString(String.Format("<span class=\"mytime\" utc =\"{0}\"></span>", date.ToString("o")));
}
So now my view just includes JQuery and script above and then does:
所以现在我的视图只包含上面的 JQuery 和脚本,然后执行:
Created at @Html.LocalDate(Model.CreatedDate)
Since this is invoked in jQuery's $() onload, it runs after the server has sent down all the times.
由于这是在 jQuery 的 $() onload 中调用的,因此它一直在服务器发送完毕后运行。
Worked like a charm!
像魅力一样工作!
回答by Kelly R
All good answers. I did mine like this:
所有的好答案。我是这样做的:
@Html.DisplayFor(m=> m.SomeDate.ToLocalTime()
.ToString(
CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern
+ " "
+ CultureInfo.CurrentUICulture.DateTimeFormat.LongTimePattern))
回答by RogueThinking
It feels like a bit of a kludge but this worked in an MVC3 client
感觉有点混乱,但这在 MVC3 客户端中有效
@DateTime.Parse(Html.DisplayFor(m=> m.SomeDate).ToString()).ToLocalTime().ToString()
回答by Athul Nalupurakkal
Use this code to convert utc time to local time
使用此代码将 UTC 时间转换为本地时间
<%: Html.DisplayFor(m=> m.SomeDate.ToLocalTime().ToString()) %>
You can use use following code in razor
您可以在剃刀中使用以下代码
@Html.DisplayFor(m=> m.SomeDate.ToLocalTime().ToString())
回答by Heemanshu Bhalla
Converting UTC Date Time To LocalDate Can be done using jquery as well. Main Benefit of doing it using jquery is in case you have hosted your website on azure. some methods given above will not work. Only one option will be left to be used that's using jquery / javascript. As Datetime.Now in case of your website is hosted on azure will return utc time for datetime.now.tolocaltime(). Please find below an example in jquery to convert UTC time to localdatetime.
将 UTC 日期时间转换为 LocalDate 也可以使用 jquery 来完成。使用 jquery 执行此操作的主要好处是,如果您将网站托管在 azure 上。上面给出的一些方法是行不通的。将只剩下一个使用 jquery / javascript 的选项。由于 Datetime.Now 如果您的网站托管在 azure 上,则会返回 datetime.now.tolocaltime() 的 UTC 时间。请在 jquery 下面找到一个示例,将 UTC 时间转换为 localdatetime。
var date = new Date('2/8/2018 3:57:48 PM UTC');
date.toString() // "Thu Feb 08 2018 21:27:48 GMT+0530 (India Standard Time)"
回答by egmfrs
In a .NET Core project, I finally had success with the following razor code:
在 .NET Core 项目中,我终于成功使用了以下 razor 代码:
@Model.DateUpdated.ToLocalTime().ToString(
CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern
+ " " +
CultureInfo.CurrentUICulture.DateTimeFormat.LongTimePattern)
(Inspiration taken from Kelly R's answer)
(灵感来自 Kelly R 的回答)