2

I’m working on ASP.NET application, and I have an issue with date formatting. TextBoxFor is displaying Date Format instead of date.

Regional Settings:

United Kingdom, date format: “yyyy-mm-dd”.

.NET Globalization - IIS Settings:

Culture:                       Invariant Language (Invariant Country)
Enable Client Based Culture:   false
UI Culture:                    Invariant Language (Invariant Country)
File:                          Windows-1252
Requests:                      utf-8
Response Headers:              utf-8
Responses:                     utf-8

MainView (I have tried ToShortDateString() and ToString("d")) :

<td>
    @item.InvoiceDate.ToShortDateString()
</td>
<td>
    @item.DueDate.ToString("d")
</td>

Edit View:

<div class="form-group">
       <div class="col-md-10">
             @Html.Label("Invoice Date:")
             <div class="fiveSpace"></div>
             @Html.TextBoxFor(model => model.InvoiceDate, "{0:d}", new { type = "date" })
             @Html.ValidationMessageFor(model => model.InvoiceDate)
       </div>
</div>

<div class="form-group">
       <div class="col-md-10">
             @Html.Label("Due Date:")
             <div class="fiveSpace"></div>
             @Html.TextBoxFor(model => model.DueDate, "{0:d}", new { type = "date" })
             @Html.ValidationMessageFor(model => model.DueDate)
       </div>
</div>

Model:

[Required(ErrorMessage = "Please select Invoice Date.")]
public DateTime? InvoiceDate { get; set; }
[Required(ErrorMessage = "Please select Due Date.")]
public DateTime? DueDate { get; set; }

And result: Table row

Once I try to edit dates: Date and Inspect element

Correct value is stored in "value" but TextBoxFor displays date format. Also, when I have changed regional setting to other country, in MainView I always received dates in format "dd/mm/yyyy" and in edit view dates were displayed with US format, "mm/dd/yyyy".

I have tried:

  • set up <globalization uiCulture="en-GB" culture="en-GB" /> in web.config
  • add [DisplayFormat(DataFormatString = "{0:d}"] to model

Is the problem on my side, or IIS?

2 Answers 2

1

Resolved.

I've replaced mentioned TextBoxFor with:

@Html.TextBoxFor(model => model.InvoiceDate, new { @type = "date", @Value = Model.InvoiceDate.Value.ToString("yyyy-MM-dd") })

and it works.

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

Comments

0

The TextBoxFor with type="date" converts it to the <input type="date"> HTML tag which doesn't support date format customization according to the MDN.

It can be achieved by some 3rd-party JS libraries like Masked Input Plugin for jQuery or datetime-input web component

Comments

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.