0

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?

rethabile
  • 3,029
  • 6
  • 34
  • 68

2 Answers2

2

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.

Lars Kristensen
  • 1,410
  • 19
  • 29
  • @StephenMuecke, That's a bit of a dramatic statement :-) I made a simple sample MVC application with the code OP posted, and verified that I could reproduce the problem. This solved the issue. There must be some settings causing the different behaviour of DisplayFormat / DataFormatString. I certainly don't have any other `DisplayTemplate` set up in my blank MVC project. – Lars Kristensen Dec 11 '17 at 09:49
1

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)
rethabile
  • 3,029
  • 6
  • 34
  • 68