120

What is wrong with the following?

@Convert.ToDateTime((@item.Date.ToShortDateString())," dd - M - yy")

@item.Date is showing 20/11/2005 12:00 a.m and I want to display 20 Nov 2011

flq
  • 22,247
  • 8
  • 55
  • 77
learning
  • 11,415
  • 35
  • 87
  • 154
  • 1
    Combinations of the various date format specifiers that exist can be found here: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx – Joseph Woodward May 15 '13 at 07:59

13 Answers13

292

Try:

@item.Date.ToString("dd MMM yyyy")

or you could use the [DisplayFormat] attribute on your view model:

[DisplayFormat(DataFormatString = "{0:dd MMM yyyy}")]
public DateTime Date { get; set }

and in your view simply:

@Html.DisplayFor(x => x.Date)
dasdom
  • 13,975
  • 2
  • 47
  • 58
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 3
    I tried this with a textbox and unfortunatly it did not work. Is there a way to do this for textboxes? – Tobias Jul 12 '11 at 11:08
  • 2
    For a textbox just use EditorFor instead of DisplayFor – Brandon シ Renfrow Jul 22 '11 at 21:03
  • 11
    Remember to set "ApplyFormatInEditMode = true" in your DisplayFormat definition if you want the date formatting to be applied to EditorFor() elements. – Latedeveloper Oct 22 '11 at 10:47
  • 1
    I needed to use this for a DateTime field in order to use the built-in date picker. Without the DisplayFormat annotation, the javascript console in the browser would show something like "The specified value '1/1/1990 12:00:00 AM' does not conform to the required format, 'yyyy-MM-dd'." I had to set both the DataFormatString and set ApplyFormatInEditMode to true for the error to go away and the value to properly display when using EditorFor in my MVC view. – Mark Jun 05 '15 at 21:02
  • This works for me, but I dunno - I get the feeling I am violating separation of concerns by applying logic to format a date (a presentation concern) in the model via an attribute. I understand this is how Microsoft expects this to work, but it just seems data display formatting should be isolated to the view and the model should just be a model. – barrypicker Jul 29 '15 at 17:47
  • [BindProperty] [DataType(DataType.Date)] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")] public DateTime EnrollmentDate { get; set; } = DateTime.Now.AddYears(-1); – Abhilash Thomas Jan 27 '23 at 05:30
83

This is solution:

@item.Published.Value.ToString("dd. MM. yyyy")

Before ToString() use Value.

Miroslav Holec
  • 3,139
  • 25
  • 22
  • 1
    this code is correct but if the date column is null, this will throw error, so try [this](http://stackoverflow.com/a/29742649/2218697) – Shaiju T Apr 20 '15 at 08:41
  • Stom is correct, if you have null values will throw you the error, thanks for the link – Nick Kahn Jun 03 '15 at 03:15
  • Just what i was looking for – Roger Tello Apr 23 '19 at 17:41
  • Null exception can be handled by using null coalescing operator - ```@(item.DOB?.ToString("dd-MMM-yyyy"))```. Or by using HasValue property - ```@(item.DataDate.HasValue ? item.DataDate.Value.Date.ToString("dd MMM yyyy") : null)```. In both cases property must be nullable datetime. – quasar Dec 11 '19 at 04:41
38

Try this in MVC 4.0

@Html.TextBoxFor(m => m.YourDate, "{0:dd/MM/yyyy}", new { @class = "datefield form-control", @placeholder = "Enter start date..." })
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
Nick
  • 391
  • 3
  • 2
22

The [DisplayFormat] attribute is only used in EditorFor/DisplayFor, and not by the raw HTML APIs like TextBoxFor. I got it working by doing the following,

Model:

[Display(Name = "When was that document issued ?")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")]
public DateTime? LiquorLicenceDocumentIssueDate { get; set; }

View:

        <div id="IsLiquorLicenceDocumentOnPremisesYes" class="groupLongLabel">
            @Html.LabelFor(m => m.LiquorLicenceDocumentIssueDate)
            <span class="indicator"></span>
            @Html.EditorFor(m => m.LiquorLicenceDocumentIssueDate)
            <span id="validEmail"></span>
            <br />
            @Html.ValidationMessageFor(m => m.LiquorLicenceDocumentIssueDate)
        </div>

Output: 30/12/2011

Related link:

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayformatattribute.applyformatineditmode.aspx

Diganta Kumar
  • 3,637
  • 3
  • 27
  • 29
10

Below code will help you

@Html.Label(@item.Date.Value.ToString("dd - M - yy"))
Anjan Kant
  • 4,090
  • 41
  • 39
5

For Razor put the file DateTime.cshtml in the Views/Shared/EditorTemplates folder. DateTime.cshtml contains two lines and produces a TextBox with a date formatted 9/11/2001.

@model DateTime?
@Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datePicker" })
Jules Bartow
  • 956
  • 14
  • 14
  • 1
    Thank you... could not get none of the others to work. Has C#/ Razor changed that much to where a simple date format has to go through so many things to work? The most suggested answer on the internet: ....ToString("dd MMM yyyy") has never worked for me and I had always ended up stuffing it into a variable converting it into a date and then outputting the date. I knew there had to be a one liner that worked somewhere. – Anthony Griggs Nov 27 '18 at 18:10
  • Anthony Griggs, I feel ya cuz. Glad to share the pain so that we all might gain --6½ years later! – Jules Bartow Dec 04 '18 at 08:14
3

In general, the written month is escaped as MMM, the 4-digit year as yyyy, so your format string should look like "dd MMM yyyy"

DateTime.ToString("dd MMM yyyy")
flq
  • 22,247
  • 8
  • 55
  • 77
3

I was not able to get this working entirely based on the suggestions above. Including the DataTypeAttribute [DataType(DataType.Date)] seemed to solve my issue, see:

Model

[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime RptDate { get; set; }

View

@Html.EditorFor(m => m.CLPosts.RptDate)

HTH

Fraze
  • 908
  • 2
  • 8
  • 20
1

For all the given solution, when you try this in a modern browser (like FF), and you have set the correct model

// Model
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime Start { get; set; }

// View
<div class="form-group">
    @Html.LabelFor(model => model.Start, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Start, "{0:dd-MM-yyyy}", new { htmlAttributes = new { @class = "form-control"} })
    </div>
</div>

mvc(5) wil render (the type of the input is set to date based on your date settings in your model!)

<div class="col-md-10">
<input class="form-control text-box single-line" data-val="true" data-val-date="The field Start must be a date." data-val-required="The Start field is required." id="Start" name="Start" value="01-05-2018" type="date">
        <span class="field-validation-valid text-danger" data-valmsg-for="Start" data-valmsg-replace="true"></span>
</div>

And the browser will show

enter image description here

To fix this you need to change the type to text instead of date (also if you want to use your custom calender)

@Html.EditorFor(model => model.Start, "{0:dd-MM-yyyy}", new { htmlAttributes = new { @class = "form-control", @type = "text" } })
Community
  • 1
  • 1
Bunkerbuster
  • 963
  • 9
  • 17
  • If I use this solution, I lose the default date picker that the `@type = "date"` provides. Is there any additional solution for this? – carloswm85 Apr 30 '22 at 15:35
  • The Answer is 4 years old (so a bit rusty on the razor / datepicker code), but I believe the whole Idea is to override the default settings of the datepicker. – Bunkerbuster May 03 '22 at 11:19
1

Based on what Anjan Kant said above, this is what I came up with (would have given you an upvote but I'm too new)

@if (Model.Quotes != null)
        {
            foreach (var item in Model.Quotes)
            {
                <tr class="code-black">
                    <td class="td">
                        @Html.Label(@item.CreateDate.ToShortDateString())
                    </td>
                    <td class="td">
                        @Html.DisplayFor(modelItem => item.Status)
                    </td>
                    <td class="td">
                        @Html.DisplayFor(modelItem => item.ProjectName)
                    </td>
                    <td class="td usd">
                        @Html.DisplayFor(modelItem => item.Total)
                    </td>
                    <td class="td">
                        <a asp-page="../Quote/Details" asp-route- 
                                        id="@item.Id">View</a> 
                    </td>
                </tr>
            }
        }
0

Easy way to change date type i.e:

   [DataType(DataType.Date)]
   public DateTime? DataEurGbp { get; set; }
Pawel
  • 38
  • 1
  • 8
0

I used this from answer in another question and it works very good:
@(item.Startdate.HasValue ? item.Startdate.Value.ToString("dd/MM/yyyy") : "Date is Empty")

if the date column is null, Value.ToString will throw error, so we use condition statement

inspired from answers by @miroslav-holec and @shaiju-t

Flowra
  • 1,350
  • 2
  • 16
  • 19
0

You can use jQuery calendar for better result, we completed this task with following code

<link rel="stylesheet" href="//code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script>
    $(function () {
        $("#EnrollmentDate").datepicker({
            dateFormat: 'dd/M/yy'//,
            //minDate: new Date(),
            //value: new Date()
        });
    });
</script>


<form method="post">

    <div class="form-group col-4">
        <label asp-for="@Model.EnrollmentDate" class="control-label"></label>
        <input class="form-control" asp-for="@Model.EnrollmentDate" type="text">
        <span asp-validation-for="@Model.EnrollmentDate" class="text-danger"></span>
    </div>

    <div class="form-group col-4">
        <input type="submit" value="SUBMIT" class="btn btn-primary btn-sm" />
    </div>

</form>

and the C# code use as follows

    [BindProperty]
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MMM/yyyy}")]
    public DateTime EnrollmentDate { get; set; } = DateTime.Now.AddYears(-1);
Abhilash Thomas
  • 833
  • 2
  • 12
  • 23