Two Ways of Formatting DateTime

Grizzly

I have a DateTime property and in my Model I have this:

[Display(Name = "Date:")]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy HH:mm}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "This field is required!")]
public Nullable<System.DateTime> Day { get; set; }

This works perfectly fine, but I have a ViewModel that is getting populated with whatever value this property holds and on the ViewModel's View I need the date to also display the tt part of a DateTime Format.

So I have tried this in the cshtml of the ViewModel:

@Html.DisplayFor(modelItem => item.Day, "{0:MM/dd/yyyy hh:mm tt}")

but this still renders without the tt. Is there a way that on some View's the display format can be MM/dd/yyyy HH:mm and on others the display format can be MM/dd/yyyy hh:mm tt for the same property?

Mihir Kale

@Html.DisplayFor(.. will always use the DisplayFormat specified on the model. So your code wont work.

In order to get the 'tt' part of the date you can try this. (since you are only displaying the datetime and not editing it)

<div>
<span> @item.Day.ToString("MM/dd/yyyy HH:mm tt") </span>
</div>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related