默认情况下,输入type="date"显示日期为YYYY-MM-DD。

问题是,是否可能将其格式强制为:DD-MM-YYYY?


当前回答

我知道这是一个老帖子,但它是谷歌搜索的第一个建议,简短的答案不,推荐答案用户自定义日期选择器,我使用的正确答案是使用文本框来模拟日期输入,并做任何你想要的格式,这里是代码

<html>
<body>
date : 
<span style="position: relative;display: inline-block;border: 1px solid #a9a9a9;height: 24px;width: 500px">
    <input type="date" class="xDateContainer" onchange="setCorrect(this,'xTime');" style="position: absolute; opacity: 0.0;height: 100%;width: 100%;"><input type="text" id="xTime" name="xTime" value="dd / mm / yyyy" style="border: none;height: 90%;" tabindex="-1"><span style="display: inline-block;width: 20px;z-index: 2;float: right;padding-top: 3px;" tabindex="-1">&#9660;</span>
</span>
<script language="javascript">
var matchEnterdDate=0;
//function to set back date opacity for non supported browsers
    window.onload =function(){
        var input = document.createElement('input');
        input.setAttribute('type','date');
        input.setAttribute('value', 'some text'); 
        if(input.value === "some text"){
            allDates = document.getElementsByClassName("xDateContainer");
            matchEnterdDate=1;
            for (var i = 0; i < allDates.length; i++) {
                allDates[i].style.opacity = "1";
            } 
        }
    }
//function to convert enterd date to any format
function setCorrect(xObj,xTraget){
    var date = new Date(xObj.value);
    var month = date.getMonth();
    var day = date.getDate();
    var year = date.getFullYear();
    if(month!='NaN'){
        document.getElementById(xTraget).value=day+" / "+month+" / "+year;
    }else{
        if(matchEnterdDate==1){document.getElementById(xTraget).value=xObj.value;}
    }
}
   </script>
  </body>
</html>

1-请注意,此方法只适用于支持日期类型的浏览器。

2- JS代码中的第一个函数是针对不支持日期类型的浏览器,并将外观设置为正常的文本输入。

3-如果你将在你的页面中使用此代码进行多个日期输入,请在函数调用和输入本身中更改文本输入的ID“xTime”,当然,使用你想要的表单提交的输入名称。

4-在第二个函数中,你可以使用任何你想要的格式,而不是日+" / "+月+" / "+年,例如年+" / "+月+" / "+日,在文本输入中使用占位符或值作为页面加载时用户的yyyy / mm / dd。

其他回答

我调整了米格尔的代码,让它更容易理解 我想和像我一样有问题的人分享。

试试这个简单快捷的方法

$("#datePicker").on("change", function(e) { displayDateFormat($(this), '#datePickerLbl', $(this).val()); }); function displayDateFormat(thisElement, datePickerLblId, dateValue) { $(thisElement).css("color", "rgba(0,0,0,0)") .siblings(`${datePickerLblId}`) .css({ position: "absolute", left: "10px", top: "3px", width: $(this).width() }) .text(dateValue.length == 0 ? "" : (`${getDateFormat(new Date(dateValue))}`)); } function getDateFormat(dateValue) { let d = new Date(dateValue); // this pattern dd/mm/yyyy // you can set pattern you need let dstring = `${("0" + d.getDate()).slice(-2)}/${("0" + (d.getMonth() + 1)).slice(-2)}/${d.getFullYear()}`; return dstring; } .date-selector { position: relative; } .date-selector>input[type=date] { text-indent: -500px; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="date-selector"> <input id="datePicker" class="form-control" type="date" onkeydown="return false" /> <span id="datePickerLbl" style="pointer-events: none;"></span> </div>

要改变格式是不可能的

我们必须区分在线格式和浏览器的表示格式。

有线格式

HTML5日期输入规范引用了RFC 3339规范,该规范指定的完整日期格式等于:yyyy-mm-dd。有关更多详细信息,请参阅RFC 3339规范的5.6节。

value HTML属性和DOM属性使用这种格式,并且在进行普通表单提交时使用这种格式。

报告格式

浏览器在显示日期输入方面是不受限制的。在编写Chrome, Edge, Firefox和Opera的日期支持(见这里)。它们都显示一个日期选择器,并在输入字段中格式化文本。

桌面设备

For Chrome, Firefox, and Opera, the formatting of the input field's text is based on the browser's language setting. For Edge, it is based on the Windows language setting. Sadly, all web browsers ignore the date formatting configured in the operating system. To me this is very strange behaviour, and something to consider when using this input type. For example, Dutch users that have their operating system or browser language set to en-us will be shown 01/30/2019 instead of the format they are accustomed to: 30-01-2019.

Internet Explorer 9、10和11显示wire格式的文本输入字段。

移动设备

特别是对于Android上的Chrome,格式是基于Android显示语言的。我怀疑其他浏览器也是如此,尽管我还没能证实这一点。

如前所述,官方不可能更改格式。然而,它可以对字段设置样式,因此(在一点JS的帮助下)它以我们想要的格式显示日期。这样就失去了操作日期输入的一些可能性,但如果强制使用格式的愿望更强烈,那么这种解决方案可能是一种方法。日期字段只保持这样:

<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">

剩下的是一些CSS和JS: http://jsfiddle.net/g7mvaosL/

$("input").on("change", function() { this.setAttribute( "data-date", moment(this.value, "YYYY-MM-DD") .format( this.getAttribute("data-date-format") ) ) }).trigger("change") input { position: relative; width: 150px; height: 20px; color: white; } input:before { position: absolute; top: 3px; left: 3px; content: attr(data-date); display: inline-block; color: black; } input::-webkit-datetime-edit, input::-webkit-inner-spin-button, input::-webkit-clear-button { display: none; } input::-webkit-calendar-picker-indicator { position: absolute; top: 3px; right: 0; color: black; opacity: 1; } <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> <input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">

它在台式机的Chrome上运行得很好,在iOS上运行得很好(尤其可取,因为在触摸屏上的本机日期操纵器是无敌的)。没有检查其他的,但是不要期望在任何Webkit上失败。

区分两种不同的格式很重要:

The RFC 3339/ISO 8601 "wire format": YYYY-MM-DD. According to the HTML5 specification, this is the format that must be used for the input's value upon form submission or when requested via the DOM API. It is locale and region independent. The format displayed by the user interface control and accepted as user input. Browser vendors are encouraged to follow the user's preferences selection. For example, on Mac OS with the region "United States" selected in the Language & Text preferences pane, Chrome 20 uses the format "m/d/yy".

HTML5规范不包括任何覆盖或手动指定这两种格式的方法。

感谢@safi eddine和@真主党Shah

Datepicker与VanillaJS和CSS。

CSS样式:

/*================== || Date Picker ||=======================================================================================*/

/*-------Removes the // Before dd - day------------------------*/
input[type="date"]::-webkit-datetime-edit-text
{
    color: transparent;    
}




/*------- DatePicker ------------------------*/
input[type="date"] {
    background-color: aqua;
    border-radius: 4px;
    border: 1px solid #8c8c8c;
    font-weight: 900;
}





/*------- DatePicker - Focus ------------------------*/
input[type="date"]:focus 
{
    outline: none;
    box-shadow: 0 0 0 3px rgba(21, 156, 228, 0.4);
}






input[type="date"]::-webkit-datetime-edit, input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-clear-button {
    color: #fff;
    position: relative;    
}



    /*------- Year ------------------------*/
    input[type="date"]::-webkit-datetime-edit-year-field {
        position: absolute !important;
        border-left: 1px solid #8c8c8c;
        padding: 2px;
        color: #000;
        left: 56px;
    }


    /*------- Month ------------------------*/
    input[type="date"]::-webkit-datetime-edit-month-field {
        position: absolute !important;
        border-left: 1px solid #8c8c8c;
        padding: 2px;
        color: #000;
        left: 26px;
    }



    /*------- Day ------------------------*/
    input[type="date"]::-webkit-datetime-edit-day-field {
        position: absolute !important;
        color: #000;
        padding: 2px;
        left: 4px;
    }

JAVASCRIPT:

 // ================================ || Format Date Picker || ===========================================================
    function GetFormatedDate(datePickerID)
    {
        let rawDate = document.getElementById(datePickerID).value; // Get the Raw Date
        return rawDate.split('-').reverse().join("-"); // Reverse the date
    }

使用:

 document.getElementById('datePicker').onchange = function () { alert(GetFormatedDate('datePicker')); }; // The datepickerID