如何比较输入中的两个日期?

时间:2016-11-26 15:15:52

标签: javascript html css date

有两个输入

From:   <input id="from" type="date" placeholder="dd/mm/yy"><br>
To:   <input id="to" type="date" placeholder="dd/mm/yy">

我想比较这两个输入,以确保结帐日期不早于入住日期。但如何比较? THX

5 个答案:

答案 0 :(得分:0)

您可以使用valueAsDate然后使用比较器:

 input1 = document.getElementById('from');
 input2 = document.getElementById('to');

 date1 = input1.valueAsDate;
 date2 = input2.valueAsDate;
 console.log(date1 < date2 ? 'valid' : 'invalid');

答案 1 :(得分:0)

如果您希望日期格式为dd / mm / yy,可以使用以下函数将字符串转换为日期:

function compareDate(str){
 // str format should be dd/mm/yyyy. Separator can be anything e.g. / or -. It wont effect
 var dt   = parseInt(str.substring(0,2));
 var mon  = parseInt(str.substring(3,5));
 var yr   = parseInt(str.substring(6,10));
 var date = new Date(yr, mon-1, dt);
 return date;
}

然后只需从输入中获取值并将它们作为日期进行比较

var input1 = compareDate(document.getElementById('from').value);
var input2 = compareDate(document.getElementById('to').value);

Date对象将执行您想要的操作 - 为每个日期构建一个,然后使用&gt;,&lt;,&lt; =或&gt; =来比较它们。

答案 2 :(得分:0)

您可以使用javascript:

获取输入的值
var fromValue = document.getElementById('from').value;
var toValue = document.getElementById('to').value;

然后使用javascript日期对象将它们转换为日期:

var fromDate = new Date(fromValue);
var toDate = new Date(toValue);

并从午夜开始删除时间:

fromDate.setHours(0,0,0,0);
toDate.setHours(0,0,0,0);

然后将fromDatetoDate进行比较:

if (fromDate === toDate) { ... }

答案 3 :(得分:0)

您可以在diff

中使用Moment.js方法
var today = new Date();
var diff = moment().diff(today, 'days');
console.log(diff); // 0

更多:http://momentjs.com/docs/#/displaying/difference/

答案 4 :(得分:0)

我就是这样做的

HTML

<script>
    function compareDates() {
        //Get the text in the elements
        var from = document.getElementById('from').textContent;
        var to = document.getElementById('to').textContent;

        //Generate an array where the first element is the year, second is month and third is day
        var splitFrom = from.split('/');
        var splitTo = to.split('/');

        //Create a date object from the arrays
        var fromDate = Date.parse(splitFrom[0], splitFrom[1] - 1, splitFrom[2]);
        var toDate = Date.parse(splitTo[0], splitTo[1] - 1, splitTo[2]);

        //Return the result of the comparison
        return fromDate < toDate;
    }
</script>

<input id="from" type="date" placeholder="dd/mm/yy"><br>
<input id="to" type="date" placeholder="dd/mm/yy">
<button onclick="compareDates()">Compare</button>

让我知道你是怎么过的。