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.
Simple and practical, use
asp-format
, example:Or:
If when defining in model does not work, you can use inside your view file:
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.
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.
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.
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?
or
I have also solved this problem using
.ToString("d")
. I received output of "MM/DD/YYYY".Try it with this in your model:
And In your controller change DateTime to Date :
Hope this help you.