Ronin
Ronin

Reputation: 7950

ASP.NET MVC5 display date in custom format

I'm trying to format a DateTime Variable so that it's being displayed as MMMM dd, yyyy, e.g. June 10, 2011.

In my view I have:

@Html.Raw(modelItem => item.MyDateTimeProperty.ToString("MMMM dd, yyyy"))

Which throws me an exception as follows:

lambda expression cannot be converted to 'string' because 'string' is not
a delegate type

Of course, the item.MyDateTimeProperty data type 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 stack247's answer is the most proper solution in an ideal environment. In my case, however, the controller returns an object which doesn't exist in my model classes. This is due I'm consuming an API to get the data. That's why Anrei's solution is best for me.

@Html.Raw(item.MyDateTimeProperty.ToString("MMMM dd, yyyy"))

[1] http://msdn.microsoft.com/en-US/library/8kb3ddd4%28v=vs.110%29.aspx

Upvotes: 3

Views: 6619

Answers (3)

stack247
stack247

Reputation: 5747

You can format date time in your View by adding annotation to your model:

[DisplayFormat(DataFormatString = "{0:MMMM dd, yyyy}")]
public DateTime ThisDate { get; set }

Then in your View:

@Html.DisplayFor(x => x.ThisDate)

Upvotes: 5

Andrei
Andrei

Reputation: 56688

Html.Raw actually expects a string as a parameter, and you are passing in a lambda. Not sure why though, you are not using lambda in any way here. So this is what error message is referring to.

Look like it should be just

@Html.Raw(item.MyDateTimeProperty.ToString("MMMM dd, yyyy"))

Upvotes: 2

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12324

@Html.Raw() method accepts a string, I think you should use @Html.DisplayFor() instead.

@Html.DisplayFor(model => model.Date) 

You can also check this question for info on applying formats I don't want error message as "The field <field> must be a date", if I am selecting date in "yyyy/MM/dd" format in en-AU locale

Upvotes: 0

Related Questions