Handling DateFormat in MVC

I am having an issues with displaying date format.

Assumption: I have not control of users's date format. So we cannot mendate or hardcode the format in our code or else I think it will not work if the date format we put in our code does not match with the user's date format (or cultural settings).

In order to help the users, I like to put a date format in a UI so that the user is clear about the date format. For instane, display Date of Birth (DD/MM/YYYY) rather Date of Birth only. So, a user will not enter 01/10/2010 when the actual date of birth is January 10, 2010 (should have entered 10/01/2010). Likewise, when we list if the UI just say 01/10/2010 without date format, it is unclear to the user whether it is January 10 or Oct 1st. So, we like to display a date format. it goes the same for when editing. We want to display a date format if possible.

I am using the same view model for all three views(Create, List, Edit).

I put the following for the view model

[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)] public DateTime DateOfBirth { get; set; }

and it lists correctly according to the format defined (and regardless of the user's cultural setting). But when editing, it will not display any date (does not show the exisitng date of birth) if the date format defined does not match the user's cultural settings.

My goal is to display a date format (any date format) to avoid the confusion when listing or entering a value.

What's the best of handle it (considering that there is no control of user's cultural settings)

1 answer

  • answered 2017-01-11 14:17 sedevel

    YOU CAN ORGANIZE BY YOURSELF

    MODEL

     [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public Nullable<System.DateTime> RegistrationDate { get; set; }
    

    VİEW

      @Html.TextBoxFor(m => m.ResgistrationDate, "{0:dd/MM/yyyy}")