简体   繁体   中英

HTML5 date of format dd/MMM/YYYY

I'm having trouble using date of format dd/MMM/YYYY on MVC5 asp.net project. Mostly on Chrome, as it seem to only accept dates of format yyyy/mm/dd.

To normalize behavior across browsers, I'm using a jquery datetimepicker component.

I have tried many things, but Chrome is still saying that the date is not valid. Even after define the input as text instead of date.

Also even if I turn off validation for that particular component (data-val="false"), Chrome still insist on marking the date as invalid.

Model:

public class order 
{
    [Key]
    public int orderID { get; set; }

    [Required]
    public string comments { get; set; }

    [Required]
    [DisplayFormat(DataFormatString = "{0:dd/MMM/yyyy}", ApplyFormatInEditMode = false)]
    [Display(Name = "Date of Shipping")]
    public DateTime date { get; set; }
}

View date input:

<div class="form-group">
    @Html.LabelFor(model => model.date, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.date, new { htmlAttributes = new { @class = "form-control datetimepicker" } })
        @Html.ValidationMessageFor(model => model.date, "", new { @class = "text-danger" })
    </div>
</div>

Imports:

<script src="https://code.jquery.com/jquery-3.2.1.js"/script>
<link rel="stylesheet" type="text/css" href="~/Content/jquery.datetimepicker.min.css" />
<script src="~/Scripts/jquery.datetimepicker.full.min.js"></script>

Javascript:

<script type="text/javascript">
    jQuery.datetimepicker.setLocale('es');

    jQuery('#date').datetimepicker({
        format: 'd/M/Y',
    });
</script>

I was finally able to fix the issue:

-Fisrt you need to add moment.js to your project, it can be added using NutGet manager, then reference on your pages:

@Scripts.Render("~/Scripts/moment-with-locales.min.js")

Very important, if working with dates on non English format, you need to import moment-with-locales as if not, even after change locale it will stay as 'en'

-Then add following java script code:

$.datetimepicker.setDateFormatter({
   parseDate: function (date, format) {
       var d = moment(date, format);
       return d.isValid() ? d.toDate() : false;
},

formatDate: function (date, format) {
    return moment(date).format(format);
    }
});

$.validator.methods.date = function (value, element) {
    return this.optional(element) || moment(value, "DD/MMM/YYYY", 'es').isValid();
}

-Also note that datetimepicker initialization changes as follows:

jQuery('#date').datetimepicker({
    format: 'DD/MMM/YYYY HH:mm',
    formatTime: 'HH:mm',
    formatDate: 'DD/MMM/YYYY'
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM