Converting DateTime format using razor

asp.net Mvc-3Razor

asp.net Mvc-3 Problem Overview


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

asp.net Mvc-3 Solutions


Solution 1 - asp.net Mvc-3

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)

Solution 2 - asp.net Mvc-3

This is solution:

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

Before ToString() use Value.

Solution 3 - asp.net Mvc-3

Try this in MVC 4.0

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

Solution 4 - asp.net Mvc-3

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

Solution 5 - asp.net Mvc-3

Below code will help you

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

Solution 6 - asp.net Mvc-3

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

Solution 7 - asp.net Mvc-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")

Solution 8 - asp.net Mvc-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

Solution 9 - asp.net Mvc-3

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

Solution 10 - asp.net Mvc-3

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

Solution 11 - asp.net Mvc-3

Easy way to change date type i.e:

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

Solution 12 - asp.net Mvc-3

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlearningView Question on Stackoverflow
Solution 1 - asp.net Mvc-3Darin DimitrovView Answer on Stackoverflow
Solution 2 - asp.net Mvc-3Miroslav HolecView Answer on Stackoverflow
Solution 3 - asp.net Mvc-3NickView Answer on Stackoverflow
Solution 4 - asp.net Mvc-3Diganta KumarView Answer on Stackoverflow
Solution 5 - asp.net Mvc-3Anjan KantView Answer on Stackoverflow
Solution 6 - asp.net Mvc-3Jules BartowView Answer on Stackoverflow
Solution 7 - asp.net Mvc-3flqView Answer on Stackoverflow
Solution 8 - asp.net Mvc-3FrazeView Answer on Stackoverflow
Solution 9 - asp.net Mvc-3BunkerbusterView Answer on Stackoverflow
Solution 10 - asp.net Mvc-3Brian TremellingView Answer on Stackoverflow
Solution 11 - asp.net Mvc-3PawelView Answer on Stackoverflow
Solution 12 - asp.net Mvc-3FlowraView Answer on Stackoverflow