20

I have problem in regarding with converting the datetime to date using a model.

Model from Class Library

public partial class LoanContract
{
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime LoanDateStart { get; set; }
}

Model from Project

public class ModelLoan
{
    public LoanContract loanContract { get; set; }
}

Code in controller

 myList.loanContract = new LoanContract { LoanDateStart = DateTime.Today };

View:

<input disabled type="date" asp-for="loanContract.LoanDateStart" id="dpDateNow" class="form-control" />

It show like this: yyyy-MM-dd what I want to achieve is that I want to change it to MM/dd/yyyy. I tried using .ToString("MM/dd/yyyy") but it doesn't work.

Tseng
  • 61,549
  • 15
  • 193
  • 205
Alvin Quezon
  • 1,089
  • 3
  • 11
  • 29
  • 2
    Please do not force tags into title. Read on [how to use tags](http://stackoverflow.com/help/tagging) for future questions. Also please make sure to use correct tags in future. [tag:asp.net] and [tag:asp.net-mvc] are **incorrect** tags for ASP.NET Core related topics. Please use [tag:asp.net-core] and [tag:asp.net-core-mvc] in future otherwise you may receive unrelated answers for the old ASP.NET instead of ASP.NET Core – Tseng May 03 '17 at 11:00
  • I will take note of that. – Alvin Quezon May 04 '17 at 00:37
  • None of the below mentioned answers and comments worked for me in asp.net core 5 – Snziv Gupta Aug 10 '21 at 10:35

10 Answers10

30

Thank you @Enrico for your comment i add it in the answer :

Try it with this in your model:

[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]

And In your controller change DateTime to Date :

myList.loanContract = new LoanContract { LoanDateStart = Date.Today };

Hope this help you.

Francois Borgies
  • 2,378
  • 31
  • 38
8

Simple and practical, use asp-format, example:

<input asp-for="MyDate" asp-format="{0:dd/MM/yyyy}" class="form-control" />

Or:

@Html.TextBoxFor(model => model.MyDate, "{0:dd/MM/yyyy}", new { @class = "form-control" })
Matheus Miranda
  • 1,755
  • 2
  • 21
  • 36
5

If when defining in model does not work, you can use inside your view file:

@String.Format("{0:dd/MM/yyyy}",ViewBag.TerminoDaAvaliacao)

This ViewBag contains a DateTime value. The time disapears with this format definition. It is not necessary to change DateTime by Date inside the Model file definition.

4

I have also solved this problem using .ToString("d"). I received output of "MM/DD/YYYY".

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
4

This might be the wrong solution to the problem being asked, but I hope it helps someone. If you are trying to input only a date (without time) Model.IsValid will throw back a validation error saying the date input format is incorrect. To solve this problem, simply Add this to your model.

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

Using data attributes inside asp.net have the benefit of automatically being supported by jQuery client-side validation. (Generated by Asp.Net)

Sludgedog
  • 331
  • 3
  • 8
2

I think it is a bug for dateformat escape chars on dotnet core. None of above solutions worked for me. Only this method solved my problem. why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

[DisplayFormat(DataFormatString = "{0:dd'/'MM'/'yyyy}", ApplyFormatInEditMode = true)]

or

<input asp-for="DateProperty" asp-format="{0:dd'/'MM'/'yyyy}">
twister
  • 320
  • 4
  • 9
1

Add [DataType(DataType.Date)] in your model

[Column(TypeName = "Date")]
[DisplayName("Date of birth")]
[DataType(DataType.Date)] 
Wasiim
  • 29
  • 1
0

(Current as of ASP.NET 6)

The problem with almost all of these answers (except the one from @Alex_Jung_89) is that they don't respect the current culture of the thread. If you operate in different locales, the custom string that you're using will not be correct if, for example, your user is hitting you from a browser that's fr-FR, because they reverse month and day from the US standard.

Tag helpers work best here without all of the annotation stuff junking up your models, and coming back in the pipe the model binder will work on the current culture of the thread.

<input type="text" asp-for="Dob" asp-format="{0:d}" />

It's also best to defer formatting to the view to keep a clear separation of concerns.

Standard format strings: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings

Jeff Putz
  • 14,504
  • 11
  • 41
  • 52
-1

For those who get here wanting to change date format of a model in the view regardless of Model class (Its what I expected to be answering). This works in both Razorpages and MVC.

Just add .ToString("dd/MM/YYYY") to the property you're displaying.

e.g.

@Model.DateOfBirth.ToString("<Use formatting here>")

This is great if you only want to show part of a date say month and year, but elsewhere you need to show the day and the time.

Mark Perry
  • 2,908
  • 3
  • 18
  • 27
-1

This might be extremely helpful sometimes,

<input asp-for="DateProperty" asp-format="**@Model.DateProperty.ToString($"{0:dd/MM/yyyy}")**">
atiyar
  • 7,762
  • 6
  • 34
  • 75
Niranjan
  • 1
  • 2