Timezone Strategy

前端 未结 4 1951
情书的邮戳
情书的邮戳 2020-12-13 06:56

I am building a MVC 3 application where the users may not be in the same time zone, so my intent was to store everything in UTC and convert from UTC to local time in the vie

4条回答
  •  萌比男神i
    2020-12-13 07:37

    You could handle the problem of converting UTC to user local time by using website-wide DisplayTemplate for DateTime.

    From your Views you would use @Html.DisplayFor(n => n.MyDateTimeProperty)

    The second problem is tougher to tackle. To convert from user local time to UTC you could override the DefaultModelBinder. Specifically the method SetProperty. Here is a naive implementation that demonstrates the point. It only applies for DateTime but could easily be extended to DateTime?. Then set it up as your Default binder in the Global.asax

    public class MyDefaultModelBinder : DefaultModelBinder
    {
        protected override void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, object value)
        {
            //special case for DateTime
            if(propertyDescriptor.PropertyType == typeof(DateTime))
            {
                if (propertyDescriptor.IsReadOnly)
                {
                    return;
                }
    
                try
                {
                    if(value != null)
                    {
                        DateTime dt = (DateTime)value;
                        propertyDescriptor.SetValue(bindingContext.Model, dt.ToUniversalTime());
                    }
                }
                catch (Exception ex)
                {
                    string modelStateKey = CreateSubPropertyName(bindingContext.ModelName, propertyDescriptor.Name);
                    bindingContext.ModelState.AddModelError(modelStateKey, ex);
                }
            }
            else
            {
                //handles all other types
                base.SetProperty(controllerContext, bindingContext, propertyDescriptor, value);
            }
        }
    }
    

提交回复
热议问题