Display DateTime value in dd/mm/yyyy format in Asp.NET MVC
Asked Answered
U

8

82

Is it possible to display a DateTime value in dd/mm/yyyy format with the help of HTML Helper methods in Asp.NET MVC? I tried to do this by using some formats in @Html.LabelFor and adding some annotations to the related property like below but it does not make any sense. Any help to solve this problem would be appreciated.

Model:

[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> RegistrationDate { get; set; }
Uvular answered 17/8, 2013 at 12:12 Comment(0)
M
65

After few hours of searching, I just solved this issue with a few lines of code

Your model

      [Required(ErrorMessage = "Enter the issued date.")]
      [DataType(DataType.Date)]
      public DateTime IssueDate { get; set; }

Razor Page

     @Html.TextBoxFor(model => model.IssueDate)
     @Html.ValidationMessageFor(model => model.IssueDate)

Jquery DatePicker

<script type="text/javascript">
    $(document).ready(function () {
        $('#IssueDate').datepicker({
            dateFormat: "dd/mm/yy",
            showStatus: true,
            showWeeks: true,
            currentText: 'Now',
            autoSize: true,
            gotoCurrent: true,
            showAnim: 'blind',
            highlightWeek: true
        });
    });
</script>

Webconfig File

    <system.web>
        <globalization uiCulture="en" culture="en-GB"/>
    </system.web>

Now your text-box will accept "dd/MM/yyyy" format.

Martres answered 1/9, 2013 at 12:54 Comment(5)
thanks mate, i was doing everything except the web.config thing but when i added your web.config line in mine, it worked perfectFavored
I tryed all that you said, but it keeps failing in one point. I'm guessing that you don't have unobtrusive jquery activated, because if you have, it throws validation errors saying that the field is not a valid date, (try a date like 31/01/2014, bcb january 31.) Try it and tell me if you have same problem. ThnksKoehler
I just added the WebConfig section it's enough to get round it - MVC5 Helpers allow you to specify a Format for the date so visible display is not an issue - I was getting stuck with a hidden field that had an AU/GB date in itKare
tried but not working,Model was set, rebuild, script was included in create view, and the view was as(( @Html.TextBoxFor(model => model.startDate, new { htmlAttributes = new { @class = "datepicker" } }))).... still in IE8 to IE 11 not workingPomerleau
This answer worked for me but dateFormat wasn't working, finally I realized I'm using Bootstrap datepicker and it's properties are different, here is details.Mandate
P
87

All you have to do is apply the format you want in the html helper call, ie.

@Html.TextBoxFor(m => m.RegistrationDate, "{0:dd/MM/yyyy}")

You don't need to provide the date format in the model class.

Practically answered 18/8, 2013 at 16:5 Comment(3)
And if you are concerned with the regional formatting you could try {0:d}Beltran
this will do noting, it's google chrome it self if you run the page in IE windows, you will not see date pickerPomerleau
It will be required to format on every page! Any global control will be appreciable!Whitewall
M
65

After few hours of searching, I just solved this issue with a few lines of code

Your model

      [Required(ErrorMessage = "Enter the issued date.")]
      [DataType(DataType.Date)]
      public DateTime IssueDate { get; set; }

Razor Page

     @Html.TextBoxFor(model => model.IssueDate)
     @Html.ValidationMessageFor(model => model.IssueDate)

Jquery DatePicker

<script type="text/javascript">
    $(document).ready(function () {
        $('#IssueDate').datepicker({
            dateFormat: "dd/mm/yy",
            showStatus: true,
            showWeeks: true,
            currentText: 'Now',
            autoSize: true,
            gotoCurrent: true,
            showAnim: 'blind',
            highlightWeek: true
        });
    });
</script>

Webconfig File

    <system.web>
        <globalization uiCulture="en" culture="en-GB"/>
    </system.web>

Now your text-box will accept "dd/MM/yyyy" format.

Martres answered 1/9, 2013 at 12:54 Comment(5)
thanks mate, i was doing everything except the web.config thing but when i added your web.config line in mine, it worked perfectFavored
I tryed all that you said, but it keeps failing in one point. I'm guessing that you don't have unobtrusive jquery activated, because if you have, it throws validation errors saying that the field is not a valid date, (try a date like 31/01/2014, bcb january 31.) Try it and tell me if you have same problem. ThnksKoehler
I just added the WebConfig section it's enough to get round it - MVC5 Helpers allow you to specify a Format for the date so visible display is not an issue - I was getting stuck with a hidden field that had an AU/GB date in itKare
tried but not working,Model was set, rebuild, script was included in create view, and the view was as(( @Html.TextBoxFor(model => model.startDate, new { htmlAttributes = new { @class = "datepicker" } }))).... still in IE8 to IE 11 not workingPomerleau
This answer worked for me but dateFormat wasn't working, finally I realized I'm using Bootstrap datepicker and it's properties are different, here is details.Mandate
K
12

I know this is an older question, but for reference, a really simple way for formatting dates without any data annotations or any other settings is as follows:

@Html.TextBoxFor(m => m.StartDate, new { @Value = Model.StartDate.ToString("dd-MMM-yyyy") })

The above format can of course be changed to whatever.

Karelian answered 23/12, 2014 at 13:25 Comment(3)
How do you solve the submitted format when server is expecting datetime and you submit some formatted string ?Isfahan
@David This save my entire week :)Cordovan
@Isfahan You need to set StartDate type as DateTime, mvc will automatically convert it into DateTimeCordovan
A
10

Since the question was "display" :

@Html.ValueFor(model => model.RegistrationDate, "{0:dd/MM/yyyy}")
Afire answered 13/3, 2017 at 21:23 Comment(0)
N
7

Or just use this in your View(Razor page)

@item.ResgistrationhaseDate.ToString(string.Format("dd/MM/yyyy"))

I recommend that don't add date format in your model class

Nutting answered 14/4, 2017 at 13:39 Comment(1)
underrated solutionElbaelbart
V
3

You need to use html helper, and you don't need to provide date format in model class. e.x :

@Html.TextBoxFor(m => m.ResgistrationhaseDate, "{0:dd/MM/yyyy}")
Vimineous answered 21/2, 2016 at 21:2 Comment(0)
C
2

It might be too late to answer this in 2019. but I tried all the answers and none worked for me. So I solved it simply this way:

@Html.EditorFor(m => m.SellDateForInstallment, "{0:dd/MM/yyyy}", 
               new {htmlAttributes = new { @class = "form-control", @type = "date" } })

EditorFor is what worked for me.

Note that SellDateForInstallment is a Nullable datetime object.

public DateTime? SellDateForInstallment { get; set; } // Model property
Cochin answered 7/9, 2019 at 16:33 Comment(0)
O
0

I made a global configuration in "Web.config" inside etiquet system web:

globalization uiCulture="en" culture="en-US

In CsHtml: @Html.TextBoxFor(model => model.fechaConfirmacion, new { @type = "date", @Value = Model.fechaConfirmacion.ToString("MM/dd/yyyy hh:mm:sszzz") })

Oulman answered 4/4, 2021 at 4:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.