125

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

1

13 Answers 13

298

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)
Sign up to request clarification or add additional context in comments.

6 Comments

I tried this with a textbox and unfortunatly it did not work. Is there a way to do this for textboxes?
For a textbox just use EditorFor instead of DisplayFor
Remember to set "ApplyFormatInEditMode = true" in your DisplayFormat definition if you want the date formatting to be applied to EditorFor() elements.
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.
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.
|
85

This is solution:

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

Before ToString() use Value.

4 Comments

this code is correct but if the date column is null, this will throw error, so try this
Stom is correct, if you have null values will throw you the error, thanks for the link
Just what i was looking for
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.
39

Try this in MVC 4.0

@Html.TextBoxFor(m => m.YourDate, "{0:dd/MM/yyyy}", new { @class = "datefield form-control", @placeholder = "Enter start date..." })

3 Comments

I don't know why would anybody downvote this answer.
I would assume the downvote was due to this solution formatting the date as "dd/MM/yyyy" rather than the "dd MMM yyyy" format that the OP requested
This one should be the chosen answer. I tried the others and none worked. thx.
23

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

1 Comment

Alternately, you could also use @string.Format("{0:MM yyyy}", imprint.VersionDate)
11

Below code will help you

@Html.Label(@item.Date.Value.ToString("dd - M - yy"))

Comments

6

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" })

2 Comments

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, I feel ya cuz. Glad to share the pain so that we all might gain --6½ years later!
4

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")

1 Comment

@ViewBag.PurchaseInfo.LastPurchaseTime.ToString("dd.MM.yyyy")
4

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

Comments

2

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" } })

2 Comments

If I use this solution, I lose the default date picker that the @type = "date" provides. Is there any additional solution for this?
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.
2

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>
            }
        }

Comments

2

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

Comments

1

Easy way to change date type i.e:

   [DataType(DataType.Date)]
   public DateTime? DataEurGbp { get; set; }

Comments

1

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.