MVC - UTC date to LocalTime

前端 未结 9 467
春和景丽
春和景丽 2020-12-28 10:07

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:<

相关标签:
9条回答
  • 2020-12-28 10:57

    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.

    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.

    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.

    After these all step you can see the result in view which contains dateTime info converted into local dateTime.

    0 讨论(0)
  • 2020-12-28 10:59

    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.

    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)"
    
    0 讨论(0)
  • 2020-12-28 11:01

    It feels like a bit of a kludge but this worked in an MVC3 client

    @DateTime.Parse(Html.DisplayFor(m=> m.SomeDate).ToString()).ToLocalTime().ToString()
    
    0 讨论(0)
提交回复
热议问题