rethabile
rethabile

Reputation: 3199

mvc view date display format

I have my date data annotation as

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreatedOn { get; set; }

In my view:

 @Html.DisplayFor(item=> item.CreatedOn)

But my date appears as just: 11 12 2017 in my view, insteaed of 11/12/2017. What ate my /'s? Anything I forgot to include?

Upvotes: 0

Views: 1827

Answers (2)

rethabile
rethabile

Reputation: 3199

It seems everything boils down to Culture info. As it currently stands it doesn't seem like we can specify CultureInfo in DisplayFormat, so i ended up defining a reusable helper method:

public static string FormatDate(this IHtmlHelper helper, DateTime date)
{
  var formattedDate = string.Format(CultureInfo.InvariantCulture, "{0:dd/MM/yyyy}", date);
  return formattedDateWithTime;
}

and in my view:

@Html.FormatDate(Model.CreatedOn)

Upvotes: 1

Lars Kristensen
Lars Kristensen

Reputation: 1495

In the format-string, wrap the / in single quotes, so your model should look something like this:

[DisplayFormat(DataFormatString = "{0:dd'/'MM'/'yyyy}")]
public DateTime CreatedOn { get; set; }

When rendered on the page, it uses the desired format.

The Documentation on DataFormatString has a remark about formatting of dates, but doesn't mention anything about this issue of formatting forward-slashes. Their proposed solution about setting HtmlEncode = true didn't work for me. I found the solution in the alternative suggestion on the answer for this similar question.

Upvotes: 2

Related Questions