3

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

1
  • this might help Commented Nov 20, 2014 at 16:55

3 Answers 3

5

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)
Sign up to request clarification or add additional context in comments.

1 Comment

This actually is better practice. You should always have everything you need to display as it is on the view by having your model ready/configured for just displaying what you need to display on the view without any logic in the view. The view should just display the data and nothing else. The model does all the necessary work
2

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

Comments

0

@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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.