111

I have the following razor code that I want to have mm/dd/yyyy date format:

Audit Date: @Html.DisplayFor(Model => Model.AuditDate)

I have tried number of different approaches but none of that approaches works in my situation

my AuditDate is a DateTime? type

I have tried something like this and got this error:

@Html.DisplayFor(Model => Model.AuditDate.Value.ToShortDateString())

Additional information: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

Tried this:

@Html.DisplayFor(Model => Model.AuditDate.ToString("mm/dd/yyyy"))

No overload for method 'ToString' takes 1 arguments

Nick Kahn
  • 19,652
  • 91
  • 275
  • 406

17 Answers17

189

If you use DisplayFor, then you have to either define the format via the DisplayFormat attribute or use a custom display template. (A full list of preset DisplayFormatString's can be found here.)

[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? AuditDate { get; set; }

Or create the view Views\Shared\DisplayTemplates\DateTime.cshtml:

@model DateTime?
@if (Model.HasValue)
{
    @Model.Value.ToString("MM/dd/yyyy")
}

That will apply to all DateTimes, though, even ones where you're encoding the time as well. If you want it to apply only to date-only properties, then use Views\Shared\DisplayTemplates\Date.cshtml and the DataType attribute on your property:

[DataType(DataType.Date)]
public DateTime? AuditDate { get; set; }

The final option is to not use DisplayFor and instead render the property directly:

@if (Model.AuditDate.HasValue)
{
    @Model.AuditDate.Value.ToString("MM/dd/yyyy")
}
TheCascadian
  • 485
  • 3
  • 14
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • I have created a displayTemplate as you suggested and when I copy and paste the code you have in template then I'm getting this error `No overload for method 'ToString' takes 1 arguments` – Nick Kahn Jan 23 '15 at 17:30
  • 4
    I think that should be `[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]` –  Jan 26 '15 at 01:09
  • [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")] worked for Turkey thanks – zapoo Apr 06 '16 at 12:14
  • @Mac: How do you mean? They very much *do* work, but perhaps just not in your specific scenario. Without more information, I cannot say what your situations is. – Chris Pratt Mar 23 '17 at 14:12
  • If you want the editor to use the format aswell, add `ApplyFormatInEditMode = true` to the property: `[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]`. It should be obvious, but when you are all no-time-to-waste-copy-paste that hint from intellisense might go past your nose as it did mine :) – Heki Jun 17 '20 at 08:14
  • Yes, but in modern web development, you should almost never actually use that. If you're using the HTML5 input types (and you should), then the edit format *must* be ISO, which is pretty much never the actual format you would also display to the user. This is yet another reason to use view models: to customize the format for the situation. – Chris Pratt Jun 17 '20 at 11:06
23

I have been using this change in my code :

old code :

 <td>
  @Html.DisplayFor(modelItem => item.dataakt)
 </td>

new :

<td>
 @Convert.ToDateTime(item.dataakt).ToString("dd/MM/yyyy")
</td>
Piotr Mirek
  • 231
  • 3
  • 3
20

If you are simply outputting the value of that model property, you don't need the DisplayFor html helper, just call it directly with the proper string formatting.

Audit Date: @Model.AuditDate.Value.ToString("d")

Should output

Audit Date: 1/21/2015

Lastly, your audit date could be null, so you should do the conditional check before you attempt to format a nullable value.

@if (item.AuditDate!= null) { @Model.AuditDate.Value.ToString("d")}

Googling the error that you are getting provides this answer, which shows that the error is from using the word Model in your Html helpers. For instance, using @Html.DisplayFor(Model=>Model.someProperty). Change these to use something else other than Model, for instance: @Html.DisplayFor(x=>x.someProperty) or change the capital M to a lowercase m in these helpers.

Community
  • 1
  • 1
Tommy
  • 39,592
  • 10
  • 90
  • 121
  • 1
    if I used `@Model.AuditDate.Value.ToString("d")` `Additional information: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.` – Nick Kahn Jan 23 '15 at 17:11
  • @AbuHamzah - sounds like you are still trying to put this in the `Html.DisplayFor` helper. Don't do that. Also, are you sure that its throwing the error on that line and not some other property you are trying to use the `DisplayFor` helper on? – Tommy Jan 23 '15 at 17:14
  • If I used `@Model...` I'm getting this error: 'Model' conflicts with the declaration System.Web.Mvc.WebViewPage.Model' – Nick Kahn Jan 23 '15 at 17:19
  • @AbuHamzah Please see the last paragraph in my updated answer. – Tommy Jan 23 '15 at 17:21
12

You can use the [DisplayFormat] attribute on your view model as you want to apply this format for the whole project.

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public Nullable<System.DateTime> Date { get; set; }
Aung San Myint
  • 181
  • 2
  • 7
  • 1
    Almost what I needed, Visual Studio did the rest for me and I neded up with `[System.ComponentModel.DataAnnotations.DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MMM yyyy}")]` and then `public DateTimeOffset MyExpirationDate { get; set; }` – Rin and Len Jan 18 '22 at 14:39
7

@ChrisPratt's answer about the use of Display Template is wrong. The correct code to make it work is:

@model DateTime?

@if (Model.HasValue)
{
    @Convert.ToDateTime(Model).ToString("MM/dd/yyyy")
}

That's because .ToString() for Nullable<DateTime> doesn't accept Format parameter.

Leonel Sanches da Silva
  • 6,972
  • 9
  • 46
  • 66
6

For me it was enough to use

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime StartDate { set; get; }
NoWar
  • 36,338
  • 80
  • 323
  • 498
  • 1
    This worked for me as well, but use this with caution. If you intend to propagate the format of the StartDate throughout your application then okay; otherwise, a more fine tune approach should be taken. – CesarB Dec 22 '22 at 01:16
5

I implemented the similar thing this way:

  1. Use TextBoxFor to display date in required format and make the field readonly.
@Html.TextBoxFor(Model => Model.AuditDate, "{0:dd-MMM-yyyy}", new{@class="my-style", @readonly=true})

2. Give zero outline and zero border to TextBox in css.

.my-style {
    outline: none;
    border: none;
}

And......Its done :)

Akshat
  • 61
  • 1
  • 5
  • 1
    But why would you do it like that? – CodeCaster May 26 '16 at 20:12
  • Because any of the other methods didn't worked for me and it saved me a lot of coding. Also, the end result is readonly and has no border, so it didn't looked like a textbox. – Akshat May 27 '16 at 09:37
4

You could use Convert

 <td>@Convert.ToString(string.Format("{0:dd/MM/yyyy}", o.frm_dt))</td> 
Karthik
  • 99
  • 7
  • this is an excellent solution, because it allows to transform the data that comes from the model without transforming the source model. – CesarB Dec 22 '22 at 14:34
3

In View Replace this:

@Html.DisplayFor(Model => Model.AuditDate.Value.ToShortDateString())

With:

@if(@Model.AuditDate.Value != null){@Model.AuditDate.Value.ToString("dd/MM/yyyy")}
else {@Html.DisplayFor(Model => Model.AuditDate)}

Explanation: If the AuditDate value is not null then it will format the date to dd/MM/yyyy, otherwise leave it as it is because it has no value.

2

Maybe try simply

@(Model.AuditDate.HasValue ? Model.AuditDate.ToString("mm/dd/yyyy") : String.Empty)

also you can use many type of string format like .ToString("dd MMM, yyyy") .ToString("d") etc

vicky
  • 1,546
  • 1
  • 18
  • 35
Wiizl
  • 359
  • 6
  • 17
2

After some digging and I ended up setting Thread's CurrentCulture value to have CultureInfo("en-US") in the controller’s action method:

Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); 

Here are some other options if you want have this setting on every view.

About CurrentCulture property value:

The CultureInfo object that is returned by this property, together with its associated objects, determine the default format for dates, times, numbers, currency values, the sorting order of text, casing conventions, and string comparisons.

Source: MSDN CurrentCulture

Note: The previous CurrentCulture property setting is probably optional if the controller is already running with CultureInfo("en-US") or similar where the date format is "MM/dd/yyyy".

After setting the CurrentCulture property, add code block to convert the date to "M/d/yyyy" format in the view:

@{  //code block 
    var shortDateLocalFormat = "";
    if (Model.AuditDate.HasValue) {
       shortDateLocalFormat = ((DateTime)Model.AuditDate).ToString("M/d/yyyy");
       //alternative way below
       //shortDateLocalFormat = ((DateTime)Model.AuditDate).ToString("d");
    }
}

@shortDateLocalFormat

Above the @shortDateLocalFormat variable is formatted with ToString("M/d/yyyy") works. If ToString("MM/dd/yyyy") is used, like I did first then you end up having leading zero issue. Also like recommended by Tommy ToString("d") works as well. Actually "d" stands for “Short date pattern” and can be used with different culture/language formats too.

I guess the code block from above can also be substituted with some cool helper method or similar.

For example

@helper DateFormatter(object date)
{
    var shortDateLocalFormat = "";
    if (date != null) {     
        shortDateLocalFormat = ((DateTime)date).ToString("M/d/yyyy");
     }

    @shortDateLocalFormat
}

can be used with this helper call

@DateFormatter(Model.AuditDate)

Update, I found out that there’s alternative way of doing the same thing when DateTime.ToString(String, IFormatProvider) method is used. When this method is used then there’s no need to use Thread’s CurrentCulture property. The CultureInfo("en-US") is passed as second argument --> IFormatProvider to DateTime.ToString(String, IFormatProvider) method.

Modified helper method:

@helper DateFormatter(object date)
{
    var shortDateLocalFormat = "";
    if (date != null) {
       shortDateLocalFormat = ((DateTime)date).ToString("d", new System.Globalization.CultureInfo("en-US"));
    }

    @shortDateLocalFormat
}

.NET Fiddle

Community
  • 1
  • 1
jyrkim
  • 2,849
  • 1
  • 24
  • 33
2

This is the best way to get a simple date string :

 @DateTime.Parse(Html.DisplayFor(Model => Model.AuditDate).ToString()).ToShortDateString()
Jesse
  • 3,522
  • 6
  • 25
  • 40
  • 3
    Here's what this answer does: takes the `HtmlString` output by `DisplayFor`, converts it to a `String`, parses it as a `DateTime`, then formats that as a `String`. Needlessly complex, in my opinion. – Heretic Monkey Sep 05 '18 at 16:54
2

Instead of

@Html.DisplayFor(Model => Model.AuditDate)

Use

@Model.AuditDate.ToString("MM/dd/yyyy")

This style renders the date as: 06/02/2022.

You can style your string accordingly to how you need it.

Suli Manack
  • 49
  • 1
  • 10
1

You just need To set Data Annotation in your Model.

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

On view(cshtml page)

@Html.DisplayFor(model => model.AuditDate)

Nothing else you need to do. Hope its useful.

0

I had a similar issue on my controller and here is what worked for me:

model.DateSigned.HasValue ? model.DateSigned.Value.ToString("MM/dd/yyyy") : ""

"DateSigned" is the value from my model The line reads, if the model value has a value then format the value, otherwise show nothing.

Hope that helps

0

You can use this instead of using @html.DisplayFor().

@Convert.ToString(string.Format("{0:dd/MM/yyyy}", Model.AuditDate))
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 10 '22 at 06:05
-1

See this answer about the No overload for method 'ToString' takes 1 arguments error.

You cannot format a nullable DateTime - you have to use the DateTime.Value property.

@Model.AuditDate.HasValue ? Model.AuditDate.Value.ToString("mm/dd/yyyy") : string.Empty

Tip: It is always helpful to work this stuff out in a standard class with intellisense before putting it into a view. In this case, you would get a compile error which would be easy to spot in a class.

Community
  • 1
  • 1
NightOwl888
  • 55,572
  • 24
  • 139
  • 212
  • if I use the suggested code then getting this error `'Model' conflicts with the declaration 'System.Web.Mvc.WebViewPage.Model'` – Nick Kahn Jan 23 '15 at 19:00