比较日期大小

有很多查询需要验证截止日期是否合理:[起始日期]不能晚于[结束日期]

以下是验证方法:

日期值一般都是通过日期控件选择产生,格式为:1999-01-01,这种格式在javascript中默认格式为:1999/01/01

因此需要比较日期首先将获取到的日期格式转换成默认格式(即1999/01/01),实现如下:

var d1 = new Date(document.getElementById('date_from').value.replace(/-/g, "/")); 
var d2 = new Date(document.getElementById('date_to').value.replace(/-/g, "/")); 

//将日期字符串转换成日期对象,进行比较
if (Date.parse(d1) - Date.parse(d2) > 0) { 
    window.alert("开始日期要小于或等于结束时间"); 
    return false;
}
    return true;
}

你可能感兴趣的:(比较日期大小)