我想将当前日期与数据库中存储的日期进行比较,我为此使用以下代码
<script>
$("#registerButton").click(function() {
var first = $("#scantime").val();
var second = $("#scanbartime").val();
if (parseInt(first.replace(/-/g,""),10) > parseInt(second.replace(/-/g,""),10)){
alert("Ticket has Expired");
}
else {
var signintime =$("#scantime").val();
var id = $("#id").val();
var y = new Date();
var y1=y.getFullYear() + "-" +(y.getMonth()+1) + "-" + y.getDate();
y.setHours(y.getHours()+4);
y1 = y1 + " " + y.getHours()+ ":" + y.getMinutes() + ":" + y.getSeconds();
document.getElementById('scanbartime').value = y1;
var expdate=y1;
$.ajax({
url: "updatescan.php",
method: "POST",
data: {signintime:signintime,expdate:expdate,id:id} ,
dataType:"text",
success: function(data)
{
}
});
}
});
</script>
scantime 的格式类似于 2016-5-26 21:31:13 , scanbartime 的格式类似于 2016-05-26 17:31:11.000000 那么为什么我使用 parseint 。 我的问题是,如果第一个大于第二个,则不会启用警报 我也尝试过
if (first > second)
但警报也不会启用 谢谢
最佳答案
我选择了以下内容:
The format of scantime Is like 2016-5-26 21:31:13 and the format of scanbartime is like 2016-05-26 17:31:11.000000
这就是如何将这些字符串转换为有效的 Date 对象格式,然后比较 Date 对象
// Turn 2016-5-26 21:31:13 into valid Date string to parse
var time1 = '2016-5-26 21:31:13';
time1 = time1.split(' ');
var split= time1[0].split('-');
for(var i = 0; i < split.length; i++){
if( split[i] < 10 )
split[i] = '0'+split[i];
}
var date1 = new Date(split.join('-') + 'T' + time1[1]);
// Turn 2016-05-26 17:31:11.000000 into a valid Date string
// The zeroes at the end dont matter
var time2 = '2016-05-26 17:31:11.000000';
time2 = time2.replace(' ', 'T');
var date2 = new Date(time2);
// Compare the dates
console.log(date1 < date2); // False
console.log(date2 < date1); // True
根据我的观察,关键的一点是月份和日期应该用零填充,并且两个字符串之间的空格应该有一个T。第二个字符串中毫秒的额外尾随零无关紧要。
关于javascript - 用javascript比较日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37463995/