Search code examples
c#.netdatemodel-view-controllerdate-format

How get the date in full string format in mvc code first approach?


I am new to MVC Code first and I was learning it by creating a sample MVC Code First CRUD Application.

Here, currently I am getting date in this format 12/16/2019 12:00:00 AM, but I am trying to display the date in 16th December 2019 format. How can I do this?

This is all I have in a class:

public class Movie
    {
        public int Id { get; set; }
        public string MovieName { get; set; }
        public string GenreName { get; set; }

        [DataType(DataType.Date)]
        public DateTime ReleasedDate { get; set; }

        [DataType(DataType.Date)]
        public DateTime DateAdded { get; set; }
    } 

EDIT:

This is my View:

@model VidlyApp.Models.Movie

@{
 ViewBag.Title = "Details";
  Layout = "~/Views/Shared/_Layout.cshtml";
 }

 <div class="col-lg-3">
      <h4><strong>Released Date: </strong> @Model.ReleasedDate</h4>
 </div>
 <div class="col-lg-3">
 <h4><strong>Added Date: </strong>@Model.DateAdded</h4>
 </div>

I have added the [DataType(DataType.Date)] Data Annotations, but doesn't seem to work.

What could be the possible solution?

Thanks.


Solution

  • You need to modify the display components @Model.ReleasedDate and @Model.DateAdded to specify the display format you require. Try

    @Model.ReleasedDate.ToString("dd MMMM yyyy")
    

    See Custom date and time format strings for definitions and examples.