0

I am trying to fetch just the date from the DateTime Entity in the View which I created in the Models. But instead it shows the whole DateTime Format

I added an Annotation [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")], but the issue remains.

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


//Adding Migration, it processed it as: 
BirthDate = table.Column<DateTime>(nullable: false)


//Index View: 
@foreach(var customers in Model)
{
 @customers.BrithDate
}

I expect the output as Friday January 1, 1990 or 1/1/1990 at least. But the output is 1/1/1990 12:00:00 AM

Wes Mes
  • 5
  • 1
  • 2

2 Answers2

0

The problem is you are outputting the model value directly. If you want to use the display formatting, you should use the following helper instead.

@Html.DisplayFor(m => customers.BirthDate)

Here are some more details in this other question as to why.

When should I use Html.Displayfor in MVC

Slicksim
  • 7,054
  • 28
  • 32
0

You have to say which DataType you want to use. I think this should solve your problem:

 [DataType(DataType.Date)]
 [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
 public DateTime? BirthDate { get; set; }

Happy coding! :)

Ronald Haan
  • 608
  • 4
  • 18
  • Thanks Man. Can you also help me with displaying the days and the month in Word format? Is it possible? – Wes Mes May 03 '19 at 11:55
  • You could look at this https://stackoverflow.com/questions/9601593/how-can-i-format-07-03-2012-to-march-7th-2012-in-c-sharp – Ronald Haan May 03 '19 at 11:59
  • That Helped.. Thank you! But How to include the Day as well? – Wes Mes May 03 '19 at 12:10
  • Therefore there is the `DayOfWeek` property. please read https://learn.microsoft.com/en-us/dotnet/api/system.datetime.dayofweek?view=netframework-4.8 – Ronald Haan May 03 '19 at 12:25