0

Tried various solutions out there related to DataFormatString but nothing is working for me for following piece of code (Date Format dd-MM-yyyy not applying in html Form)

 [Column("dateOfBirth")]
 [Required]
 [DataType(DataType.Date), DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
 [Display(Name = "Date Of Birth")]
 public virtual DateTime DateOfBirth { get; set; }

and Inside the html

 <div class="form-group">
     @Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
         @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" } })
         @Html.ValidationMessageFor(model => model.DateOfBirth, "", new { @class = "text-danger" })
     </div>
 </div>
Brian Mains
  • 50,520
  • 35
  • 148
  • 257
gmuhammad
  • 1,434
  • 4
  • 25
  • 39
  • What is happening? Are you trying to display the browsers HTML-5 datapicker? –  Aug 16 '17 at 13:29
  • date picker is showing properly but the format is mm/dd/yyyy instead of dd-MM-yyyy – gmuhammad Aug 16 '17 at 13:30
  • Its needs to be `DataFormatString = "{0:yyyy-MM-dd}"` (ISO format). The whole point of the HTML-5 datepicker is to render the date in the culture of the users browser. –  Aug 16 '17 at 13:31
  • Refer also [this answer](https://stackoverflow.com/questions/43820926/specify-date-format-in-mvc5-dd-mm-yyyy/43826746#43826746) –  Aug 16 '17 at 13:33
  • Can we override this behavior ? I mean It's my App requirement to show in dd-MM-yyyy format. – gmuhammad Aug 16 '17 at 13:33
  • Then use a jquery datepicker (you cannot control the users browser) –  Aug 16 '17 at 13:33
  • OK. from end user point of view If user wants the date time picker to use dd-MM-yyyy format. Then how he/she can set it ? I mean where in Chrome user can set this format ? – gmuhammad Aug 16 '17 at 13:37
  • Also if I as developer digest this behavior but want to store dd-MM-yyyy in db then what changes need to be done before ` db.Employees.Add(employee); db.SaveChanges(); ` – gmuhammad Aug 16 '17 at 13:40
  • try adding `value` inside `EditorFor` like `@Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control" ,@Value=Model.DateOfBirth.ToShortDateString()} })` – Ghanshyam Singh Aug 16 '17 at 14:10
  • You cannot change it (you have no control over how the browser renders its HTML-5 date picker). Again, use a jquery datepicker (e.g. [jquery-ui datepicker](https://jqueryui.com/datepicker/) which will give you full control. –  Aug 16 '17 at 22:30

0 Answers0