简体   繁体   中英

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 , eg 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

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)

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"))

@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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM