learning
learning

Reputation: 11725

Converting DateTime format using razor

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

Upvotes: 125

Views: 365807

Answers (13)

Abhilash Thomas
Abhilash Thomas

Reputation: 863

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

Upvotes: 1

Flowra
Flowra

Reputation: 1408

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

Upvotes: 2

Pawel
Pawel

Reputation: 48

Easy way to change date type i.e:

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

Upvotes: 1

Brian Tremelling
Brian Tremelling

Reputation: 45

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

Upvotes: 2

Fraze
Fraze

Reputation: 948

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

Upvotes: 4

Bunkerbuster
Bunkerbuster

Reputation: 1001

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

Upvotes: 2

Anjan Kant
Anjan Kant

Reputation: 4316

Below code will help you

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

Upvotes: 11

Nick
Nick

Reputation: 401

Try this in MVC 4.0

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

Upvotes: 39

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

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)

Upvotes: 298

Jules Bartow
Jules Bartow

Reputation: 966

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

Upvotes: 6

Diganta Kumar
Diganta Kumar

Reputation: 3681

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

Upvotes: 23

Miroslav Holec
Miroslav Holec

Reputation: 3217

This is solution:

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

Before ToString() use Value.

Upvotes: 84

flq
flq

Reputation: 22829

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

Upvotes: 4

Related Questions