javascript 如何在 jQuery 中解析日期字符串并检查它是否在过去
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13532366/
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
How to parse date string in jQuery and check if it is in the past
提问by AJFMEDIA
I need to check if the date is in the past. This is what I have so far. JSfiddle here.
我需要检查日期是否在过去。这就是我迄今为止所拥有的。JSfiddle 在这里。
var date = "09/12/2013";
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var todaysDate = +(('' + day).length < 2 ? '0' : '') + day + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + d.getFullYear();
if (date < todaysDate) {
alert("in the past");
} else {
alert("in the future");
}
Currently it is saying that the date was in the past, when it should be in the future. I know I need to parse the string as a date, but not sure how.
目前它说日期是过去的,什么时候应该是将来的。我知道我需要将字符串解析为日期,但不确定如何解析。
Help?
帮助?
回答by T.J. Crowder
With that input format, you can't use a string comparison, because the least significant values are on the left. Note: I'm assuing that date is December 9th, 2013. If you're doing the American thing where it's September 12th, 2013, you'll have to adjust the indexes into parts
below.
使用该输入格式,您不能使用字符串比较,因为最不重要的值在左侧。注意:我假设该日期是 2013 年 12 月 9 日。如果您在 2013 年 9 月 12 日的美国做事,则必须将索引调整为parts
以下。
You couldreverse the fields:
您可以反转字段:
var date = "09/12/2013";
var parts = date.split('/');
date = parts[2] + "/" + parts[1] + "/" + parts[0];
...and then do your string comparison (being sure to construct the string for "today" in the same order — year/month/day).
...然后进行字符串比较(确保以相同的顺序构造“今天”的字符串——年/月/日)。
If you're going to do that, you could go ahead and finish the job
如果你打算这样做,你可以继续完成这项工作
var date = "09/12/2013";
var parts = date.split('/');
var date = new Date(parseInt(parts[2], 10), // year
parseInt(parts[1], 10) - 1, // month, starts with 0
parseInt(parts[0], 10)); // day
if (date < new Date()) {
// It's in the past, including one millisecond ago
}
...but of course, if you don't want the expression to be true for one millisecond ago, your string approach is fine.
...但当然,如果您不希望表达式在一毫秒前为真,那么您的字符串方法就可以了。
回答by dda
var date = new Date("09/12/2013");
var d = new Date();
console.log(date>d); // true
var date = new Date("09/12/2011");
console.log(date>d); // false
回答by EMMERICH
JavaScript's native Date comparator only works on Date objects, whereas you are comparing Strings. You should parse date
into a Date
object, and then compare it with d
.
JavaScript 的本机日期比较器仅适用于日期对象,而您正在比较字符串。您应该解析date
为一个Date
对象,然后将其与d
.
//define parse(string) --> Date
if(parse(date) < new Date()) {
alert('past');
} else {
alert('future');
}