比较日期在javascript中未返回正确的结果
我正在用javascript比较两个日期比较日期在javascript中未返回正确的结果,javascript,Javascript,我正在用javascript比较两个日期 function checkCurrentDate(expiryDate){ //var currentDateStr=expiryDate; var currentDate = new Date(); var month = currentDate.getMonth() + 1; var day = currentDate.getDate(); var year = currentDate.getFullYear(); currentDate = mo
function checkCurrentDate(expiryDate){
//var currentDateStr=expiryDate;
var currentDate = new Date();
var month = currentDate.getMonth() + 1;
var day = currentDate.getDate();
var year = currentDate.getFullYear();
currentDate = month + "/" + day + "/" + year;
var dArr = currentDate.split("/");
currentDate = dArr[0]+ "/" +dArr[1]+ "/" +dArr[2].substring(2);
var currentExpiryDateStr = expiryDate;
if(currentExpiryDateStr == currentDate){
}
if(currentExpiryDateStr < currentDate){
alert("Expiry date is earlier than the current date.");
return false;
}
}
函数检查当前日期(到期日期){
//var currentDateStr=到期日;
var currentDate=新日期();
var month=currentDate.getMonth()+1;
var day=currentDate.getDate();
var year=currentDate.getFullYear();
当前日期=月+“/”+日+“/”+年;
var dArr=currentDate.split(“/”);
currentDate=dArr[0]+“/”+dArr[1]+“/”+dArr[2]。子字符串(2);
var currentExpiryDateStr=expiryDate;
如果(currentExpiryDateStr==currentDate){
}
如果(currentExpiryDateStr
当前日期在“currentExpiryDateStr”中是“11/10/12”,而“currentDate”是“11/8/12”,现在处于这种情况下“如果(currentExpiryDateStr
function checkCurrentDate(expiryDate){
var currentDate = new Date(); // now date object
var currentExpiryDateStr = new Date(expiryDate); //expiry date object
if(currentExpiryDateStr == currentDate){
}
if(currentExpiryDateStr < currentDate){
alert("Expiry date is earlier than the current date.");
return false;
}
}
函数检查当前日期(到期日期){
var currentDate=new Date();//现在是日期对象
var currentExpiryDateStr=新日期(expiryDate);//到期日期对象
如果(currentExpiryDateStr==currentDate){
}
如果(currentExpiryDateStr
这是小提琴::只需在if条件之前添加这两行即可
currentExpiryDateStr=Date.parse(currentExpiryDateStr);
currentDate=Date.parse(currentDate);
var currentDate=Date.now();
if(expiryDate.getTime()
now()
方法以数字形式返回自1970年1月1日00:00:00 UTC至今经过的毫秒数
getTime()
返回自1970年1月1日午夜以来的毫秒数如果要比较字符串,则应该比较日期对象
如果expriy日期为'11/10/12',格式为月/日/年,且年份为2000年后的两位数年份,则可以使用以下方法将其转换为日期:
function mdyToDate(dateString) {
var b = dateString.split(/\D/);
return new Date('20' + b[2], --b[0], b[1]);
}
要测试到期,可以执行以下操作:
function hasExpired(dateString) {
var expiryDate = mdyToDate(dateString);
var now = new Date();
return now > expiryDate;
}
因此,2012年11月8日:
hasExpired('11/10/12'); // 10-Nov-2012 -- false
hasExpired('6/3/12'); // 03-Jun-2012 -- true
haspeired
功能可以替换为:
if (new Date() > mdyToDate(dateString)) {
// dateString has expired
}
-1 Date.parse不应用于分析字符串,因为跨浏览器的一致性较差。提供非标准格式尤其糟糕。如果要使用它,那么应该使用一种格式(例如ISO8601),尽管它在某些浏览器中会失败,并且应该检查结果。Rob我也看到了你的方法,但有一个问题。如果我检查相等(=)条件。然后它失败了,因为它也是在比较时间
if (new Date() > mdyToDate(dateString)) {
// dateString has expired
}