1

Using ASP.NET 5 Web Application Template I am trying to render a date in short date format. My viewmodel looks like this

    [Display(Name = "Subscription Expires")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
    public DateTime? SubscriptionExpires { get; set; }

My view looks like this

    <dt><label asp-for="SubscriptionExpires"></label>:</dt>
<dd>
    @Model.SubscriptionExpires
</dd>

However @Model.SubscriptionExpires renders in long date format. How do I get the view to render the date in short date format?

1 Answer 1

1

You're directly outputting the date to the page, there is no opportunity for your data annotations to be considered.

HTML helpers look at those annotations, so you could simply do this:

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

Alternatively simply format the date like this:

@Model.SubscriptionExpires.ToShortDateString()

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @Mister Epic. 'ToShortDateString()' can't be used with nullable types but '@Html.DisplayFor(model => model.SubscriptionExpires)' did the trick.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.