7

In an ASP.NET Core project I have to display a (readonly) date in a specific format (say "dd/mm/yyyy HH:MM")

<div class="form-group">
    <label asp-for="Date" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <input asp-for="Date" readonly class="form-control" />
    </div>
</div>

How can I do it, knowing that the Date field is declared in the model like this

public DateTime Date { get { return this.Timestamp.DateTime; } }

?

serge
  • 9,891
  • 17
  • 84
  • 142

4 Answers4

13

Try this.

<input asp-for="Date" asp-format="{0:dd/MM/yyyy HH:mm}" readonly class="form-control" />
tsu1980
  • 2,036
  • 1
  • 22
  • 11
11

Alternatively, you could decorate the property with DisplayFormatAttribute.

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy HH:MM}")]
public DateTime Date { get { return this.Timestamp.DateTime; } }

The markup you have would not need to change.

Will Ray
  • 9,513
  • 3
  • 39
  • 57
  • I tried this and found it threw an error when the underlying datatype didnt conform to the DataFormatString pattern; i.e.with a format of {dd/MM/yyyy}, becuase my underlying data was a DateTime with HH:MM, I got an exception – RichyRoo Oct 03 '19 at 13:37
4

If it is read only, you could hardcode as -

<input value="@Model.Date.ToString("dd/MM/yyyy HH:mm")" readonly class="form-control" />

Or display as text

<div class="form-group">
    <label asp-for="Date" class="col-md-2 control-label"></label>
    <div class="col-md-10 form-control-static">
        @Model.Date.ToString("dd/MM/yyyy HH:mm")
    </div>
</div>
Win
  • 56,078
  • 13
  • 92
  • 167
2

Using ASP.Core TagHelpers as per your question;

[DataType(DataType.Date)]
public DateTime Date { get { return this.Timestamp.DateTime; } }

will format the input fields nicely in accordance with your locale setting. I haven't found a tag helper solution for any other tags, looks like hardcoding as per Win's answer

RichyRoo
  • 151
  • 1
  • 5