How to change date and time format in MVC 3

I have a code.

Model

    [Required(ErrorMessage = "Bạn hãy nhập ngày tháng năm sinh")]
    [DataType(DataType.Date, ErrorMessage = "Ngày tháng năm sinh không chính xác, bạn hãy nhập lại")]
    [ValidationHelper.DateFormat(ErrorMessage = "Ngày tháng năm sinh không chính xác, bạn hãy nhập lại")]
    [DisplayFormat(DataFormatString = "{MM/dd/yyyy}")]
    [Display(Name = "Ngày sinh")]
    public System.DateTime DateOfBirth { get; set; }

View

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>


@using (Html.BeginForm((string)ViewBag.FormAction, "Account"))
{
    <fieldset>
        <legend>Registration Form</legend>
        <ol>

            <li>
                @Html.LabelFor(m => m.DateOfBirth)
                @Html.EditorFor(m => m.DateOfBirth)
                @Html.ValidationMessageFor(m => m.DateOfBirth)
            </li>
        </ol>
    </fieldset>
}

when I enter 05/31/2012 => The value '05 / 31/2012 'is not valid for the Ngày cấp CMT. when I enter 05/05/2012 => The Ngày cấp CMT field must be a date. What happened? I am from Vietnam. My English is very poor, but please help me! Thank you so much! My local date format is yyyy / MM / dd

+3
source share
3 answers

Try:

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

or you can use the attribute [DisplayFormat]in your view model:

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

and, in your opinion, simply:

@Html.DisplayFor(x => x.Date)
+2
source

To make it DisplayFormatwork with EditorFor, you need to add ApplyFormatInEditModeas follows:

[DisplayFormat(DataFormatString="{0:MM/dd/yyyy}", ApplyFormatInEditMode=true)]

+2
source

, :

[DisplayFormat(DataFormatString = "{MM/dd/yyyy}")]

, 31/05/2012 , :

[DisplayFormat(DataFormatString = "{dd/MM/yyyy}")]
0

All Articles