ASP.NET MVC5 show date in custom format
I am trying to format a DateTime variable so that it appears like MMMM dd, yyyy
eg. June 10, 2011
In my opinion, I have:
@Html.Raw(modelItem => item.MyDateTimeProperty.ToString("MMMM dd, yyyy"))
Which throws me an exception like this:
lambda expression cannot be converted to 'string' because 'string' is not
a delegate type
Of course, the data type item.MyDateTimeProperty
is DateTime
.
For reference, I used the following example [1]
// The example displays the following output:
// Today is June 10, 2011.
DateTime thisDate1 = new DateTime(2011, 6, 10);
Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");
What am I doing wrong?
EDIT
I see that the answer stack247
is the most correct solution in an ideal environment. However, in my case, the controller is returning an object that doesn't exist in my model classes. This is because I am using an API to get data. So the solution is Anrei
better for me.
@Html.Raw(item.MyDateTimeProperty.ToString("MMMM dd, yyyy"))
[1] http://msdn.microsoft.com/en-US/library/8kb3ddd4%28v=vs.110%29.aspx
source to share
@Html.Raw()
the method takes a string, I think you should use @Html.DisplayFor()
instead.
@Html.DisplayFor(model => model.Date)
You can also check this question for information on using formats I don't want the error message to be like "Field <field> must be a date" if I select the date in "yyyy / MM / dd" format in the local AU-AU directory
source to share