Date now greater than date value given
I am having to try to determine whether a date from a hidden field, formatted mm/dd/yyyy, is less than today. if it is, I want to let the person know that a subscription has expired. I have had this working on some occasions but it is not reliably doing it??
//this is the expiration date that is in a hidden field
var expireDate = $("#exp开发者_如何学JAVAire").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");
};
You're comparing the numerical value of strings, which happen to be the string representation of dates in mm/dd/yyyy format. I'm guessing that your "inconsistent" results are that it works if the old date is an earlier month than today.
Instead of converting a to a string, convert expireDate to a Date object. Then compare.
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");
};
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");
};
other thread
simpler IMO:
var startDt=document.getElementById("startDateId").value;
var endDt=document.getElementById("endDateId").value;
if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
{
----------------------------------
}
精彩评论