6

I work in MVC5 and EntityFramework for displaying data into View.

right now in my view data format is :- 10/22/2014 12:00:00 AM But i want only date :- 22/10/2014 in this format

i try this code but it not working

 @if (item.chekin_on_after != null)
                    { @Html.DisplayFor(modelItem => item.chekin_on_after, "ShortDateTime")}

I also follow few link in stackoverflow but not helpful Date Format using Html.DisplayFor() in MVC5, Display only date and no time

Community
  • 1
  • 1
ANJYR
  • 2,583
  • 6
  • 39
  • 60
  • You could add the `[DisplayFormat]` attribute to your property or create a custom `DisplatTemplate` to format the date –  Oct 20 '14 at 11:45
  • my model class generated by database, Entity Framework, if in future, i will update my DataModel then it will lost. – ANJYR Oct 20 '14 at 12:19
  • 1
    That why its best practice to use view models to represent the data you want to display –  Oct 20 '14 at 12:21

3 Answers3

25

I didn’t use @html.DisplayFor().Instead of this I use

@Convert.ToString(string.Format("{0:dd/MM/yyyy}", item.chekin_on_after))

And it works perfectly.

xrisk
  • 3,790
  • 22
  • 45
ANJYR
  • 2,583
  • 6
  • 39
  • 60
  • Yes, but if you are trying to use Model binding, @Html.DisplayFor is what you normally want to use. If you are not using Model binding then your example will work. – John Foll Apr 21 '23 at 01:53
6

Try to use below attribute in your model class.

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

Hope it helps..

Nirav Parmar
  • 451
  • 3
  • 12
2

You can use this function in your controller before populating the data to model :

public static System.DateTime ParseDate(string value, string style)
{
    DateTime blankDate = default(DateTime);
    if ((value != null & value.Length > 0)) {
        string formattedDate = Strings.Format(Convert.ToDateTime(value), style);
        return formattedDate;
    } else {
        return blankDate;
    }
}

Where value is your: 10/22/2014 12:00:00 AM and style is :"MM/dd/yyyy" or something as you want

Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
  • My Model and View is generated by Entity Framework and it return a **LIST** so where i put this code. I am little confuse how i use this code. – ANJYR Oct 20 '14 at 12:44