我不得不尝试确定隐藏字段中的日期(格式为mm / dd / yyyy)是否小于今天。如果是,我想让这个人知道订阅已经过期。我曾经在某些情况下使用它,但它不能可靠地进行吗?
//this is the expiration date that is in a hidden field
var expireDate = $("#expire").val();
//here I am trying to setup a new date for today and change the output to match the date
//format for the hidden field, i.e. mm/dd/yyyy
var a = new Date();
var b = a.toISOString().split("T")[0].split("-");
var ca = b[1] + "/" + b[2] + "/" + b[0];
//now I want to compare the 2 and if the expiration date is less than today, display a warning message
if (expireDate < ca) {
$("<div class=\"message-warning\">This subscription is expired</div>")
.insertAfter("#enddate");
};
答案 0 :(得分:16)
您正在比较字符串的数值,这恰好是以mm / dd / yyyy格式表示日期的字符串表示形式。我猜你的“不一致”结果是,如果旧日期比今天早,那么它可以工作。
不是将a转换为字符串,而是将expireDate转换为Date对象。然后比较。
var expireDateStr = $("#expire").val();
var expireDateArr = expireDateStr.split("/");
var expireDate = new Date(expireDateArr[2], expireDateArr[0], expireDateArr[1]);
var todayDate = new Date();
if (todayDate > expireDate) {
$("<div class=\"message-warning\">This subscription is expired</div>")
.insertAfter("#enddate");
};
答案 1 :(得分:4)
var expireDate = $("#expire").val().split('/'),
expireYear = parseInt(expireDate[2], 10), // cast Strings as Numbers
expireMo = parseInt(expireDate[0], 10),
expireDay = parseInt(expireDate[1], 10);
var now = new Date(),
nowYear = now.getFullYear(),
nowMo = now.getMonth() + 1, // for getMonth(), January is 0
nowDay = now.getDate();
// don't expire until day after expiry date
if (nowYear > expireYear ||
nowYear == expireYear && nowMo > expireMo ||
nowYear == expireYear && nowMo == expireMo && nowDay > expireDay) {
$("<div class=\"message-warning\">This subscription is expired</div>")
.insertAfter("#enddate");
};
答案 2 :(得分:0)
更简单的IMO:
var startDt=document.getElementById("startDateId").value;
var endDt=document.getElementById("endDateId").value;
if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
{
----------------------------------
}