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

+3


source to share


3 answers


Html.Raw

does indeed expect a string as a parameter and you are passing into a lambda. Not sure why, although you are not using lambda here. So this is an error message.

It looks like it should be simple



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

      

+2


source


You can format the date 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)

      

+5


source


@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

0


source







All Articles