-1

How to render a DateTime in a specific format in ASP.NET MVC 3 using @Html.DisplayFor(.....)? If I have in my model class a property of type DateTime how can I render it in a specific format.

Data Annotation:
        [DisplayName("Created On")]
        [DataType(DataType.Date)]
        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
        public object CreatedOn { get; set; }

View:

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

it displaying only Date in mm/dd/yyyy format, but i want dd/mm/yyyy hh: mm:ssss or mm/dd/yyyy hh: mm:ssss in this format.

Jaimin
  • 7,964
  • 2
  • 25
  • 32
Boss
  • 445
  • 2
  • 8
  • 24

4 Answers4

1

You can use DisplayFormat attribute, see MSDN Ref

[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", 
                                                  ApplyFormatInEditMode = true)]
public DateTime YourDateTime { get; set; }
Imad Alazani
  • 6,688
  • 7
  • 36
  • 58
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • @PKKG Attribute parameters must be constants. For an application that handles multiple cultures, the date format string is not constant. Therefore this method using attributes is not a good solution for multi-cultural applications. – Oliver Aug 19 '13 at 13:33
  • @PKKG If the format was hard-coded in the model, or if the application was designed only for 'dd/MM/yyyy', then the application is NOT multi-cultural. My comment of "This isn't a good solution for multi-cultural applications." still stands true for this solution. – Oliver Aug 19 '13 at 13:48
  • Stop it guys Oliver and PKKG, You both are correct in there respective thinking. Lets have peace – Satpal Aug 19 '13 at 14:00
  • @PKKG & Satpal All friendly here, just clarifying my point :). The difference is that in my example, the string can be replaced with a variable containing the date format of the user, whereas this is not possible with attribute parameters. – Oliver Aug 19 '13 at 14:05
1

If your requirement just showing date and time in the format of dd/mm/yyyy hh: mm:ssss, no need to use DisplayFor(), use like below it displays date and time

 @item.CreatedOn
Rajesh
  • 86
  • 3
0

If you want to render the DateTime in a SPECIFIC format, you could just render the DateTime using ToString() and pass the format string that you require:

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

Otherwise, @Html.DisplayFor(model => model.DateField) will use the format defined in the thread's culture.

The thread's culture can be set to automatically use the client's culture (using the Accept-Language request header) in the web.config file:

  <system.web>
    <globalization enableClientBasedCulture="true" />
  </system.web>
Oliver
  • 8,794
  • 2
  • 40
  • 60
0

You can use the ToString() method for your problem.

Datevalue.ToString("dd.MM.yyyy");

or

Datevalue.ToString("MM/dd/yyyy");
Imad Alazani
  • 6,688
  • 7
  • 36
  • 58
Marco
  • 22,856
  • 9
  • 75
  • 124