jQuery 日期现在大于给定的日期值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7396526/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Date now greater than date value given
提问by pertrai1
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??
我必须尝试确定格式为 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");
};
回答by torstenvl
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.
您正在比较字符串的数值,这恰好是 mm/dd/yyyy 格式的日期字符串表示形式。我猜你的“不一致”结果是,如果旧日期比今天早一个月,它就会起作用。
Instead of converting a to a string, convert expireDate to a Date object. Then compare.
不是将 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");
};
回答by mVChr
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");
};
回答by AZ Chad
simpler IMO:
更简单的海事组织:
var startDt=document.getElementById("startDateId").value;
var endDt=document.getElementById("endDateId").value;
if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
{
----------------------------------
}