我在StackOverflow的帮助下制作了一个非常好的日期掩码。似乎工作主要是因为我使用日期函数而不是hacky splits切片。但我有一个bug可能需要一些切片和替换。所以下面的代码基本上是将所有日期格式化为月/日/年(00/00/0000)格式。典型的1-2-91,01-1-1991等都正确格式化,除非我不使用分隔符并输入日期,如' 01011991'(想要01/01/1991),其回馈无效日期/楠。我正在考虑所有场景,这个序列应该有效,因为只有丢失的东西是斜线。它甚至格式化为01/01/2001,当时我只放了' 1'在现场
function execute () {
var new_date = document.getElementById('date_val').value;
var j = format(new_date);
document.getElementById('date_val').value = j;
}
function format(incoming_date) {
var d = new Date(incoming_date);
console.log('new date', d)
day = d.getDate();
month = d.getMonth() + 1;
year = d.getFullYear();
return (String(month).length == 1 ? '0' + month : month) + '/' + (String(day).length == 1 ? '0' + day : day) + '/' + year;
};

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
date: <input type="text" id="date_val" onblur="execute()">
<!-- <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="./js/test.js"></script> -->
<script src="./js/test.js"></script>
</body>
</html>
&#13;
答案 0 :(得分:0)
所以基本上做了一个关键功能,检查并添加&#39; /&#39;对于前两天(日和月)
function execute () {
var new_date = document.getElementById('date_val').value;
var a = new_date.replace(/\//gi, "-");
var j = format(a);
document.getElementById('date_val').value = j;
}
function format(incoming_date) {
console.log("check entered",incoming_date)
var d = new Date(incoming_date);
console.log('new date', d)
day = d.getDate();
console.log('check day',day);
month = d.getMonth() + 1;
console.log('check month',month);
year = d.getFullYear();
console.log('check year',year);
return (String(month).length == 1 ? '0' + month : month) + '/' + (String(day).length == 1 ? '0' + day : day) + '/' + year;
};
function onkey(){
var e = document.getElementById('date_val');
var numChars = e.value.length;
if(numChars === 2 || numChars === 5){
var thisVal = e.value;
thisVal += '/';
e.value = thisVal;
}
}
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" id="date_val" onkeyup="onkey()">
<!-- <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="./js/test.js"></script> -->
<script src="./js/test.js"></script>
</body>
</html>
&#13;