javascript验证过去的日期

时间:2014-04-28 12:50:21

标签: validation date

我想比较某个特定日期是过去还是将来 给定日期来自yyyy-mm-dd格式的字符串 我试图“平衡”今天并在给定的日期日期补偿时区,但我确信必须有更好的方法吗?

var today           = new Date();
console.log("TODAY: " + today); // Mon Apr 28 2014 14:46:41 GMT+0200 (CEST)
var todayYear       = today.getFullYear();
var todayMonth      = today.getMonth();
todayMonth          = parseInt(todayMonth, 10) + 1;
var todayDay        = today.getDate();
var todayFormatted  = todayYear + "-" + todayMonth + "-" + todayDay;
today               = new Date(todayFormatted);
console.log("TODAY: " + today); // Mon Apr 28 2014 00:00:00 GMT+0200 (CEST)
var testDate        = new Date("2014-04-28");
console.log("TEST: " + testDate); // Mon Apr 28 2014 02:00:00 GMT+0200 (CEST)
testDate.setHours(00);
console.log("TEST: " + testDate);
// check if test is in the past
(testDate < today) ? console.log('test is in the past') : console.log('test is NOT in the past');

1 个答案:

答案 0 :(得分:0)

您可以比较&#34; Unix时间&#34;数学:

var today = new Date();
console.log(testDate.getTime() < today.getTime()
 ? 'test is in the past'
 : 'test is NOT in the past');