【发布时间】:2013-04-01 11:55:06
【问题描述】:
我想在 jquery 中按日期比较一些消息。
例如:
我有一个 文本框 值作为04/01/2013 13:15:32 由用户端填充。
并且 jquery 变量中的当前日期时间为04/01/2013 18:30:12
如果文本框值小于当前日期时间,则显示一条消息:
function foo(){
usrDate = jQuery("#txtDate").val(); //getting user input date time
currentDate = new Date(); //system current date
currentMonth = currentDate.getMonth() + 01;
currentDay = currentDate.getDate();
currentYear = currentDate.getFullYear();
currentHours = currentDate.getHours();
currentMinutes = currentDate.getMinutes();
currentSeconds = currentDate.getSeconds();
currentcpDateTime = currentMonth + "/" + currentDay + "/" + currentYear + " " + currentHours + ":" + currentMinutes + ":" + currentSeconds;
if (usrDate > currentcpDateTime ) {
alert("you can not choose date greater then current");
}
else {
alert("valid date");
}
}
每次都是错误的结果。 :(
【问题讨论】:
-
当您应该比较日期对象时,您正在比较字符串。基本上你是在倒退,因为你应该将
usrDate字符串转换为日期对象,而不是将current****中的日期对象转换为字符串。 -
为什么不使用纯javascript?使用
gettime()函数将日期转换为刻度,然后您可以比较两个数字。 -
使用
if(Date.parse(usrDate) > Date.parse(currentcpDateTime)) -
您实际上可以将日期作为字符串进行比较,但如果您使用
month/day/year格式则不能。与在文件名中添加日期时相同。
标签: jquery