jQuery 比较两个javascript字符串日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19524577/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 00:09:51  来源:igfitidea点击:

Compare two javascript string dates

javascriptjquery

提问by David542

How would I compare the following two dates?

我将如何比较以下两个日期?

var start_date = $('#start_date').text();
var end_date = $('#end_date').text();
alert(start_date + ' ' + end_date); // '2013-01-01 2013-01-02'

# how to do the following?
if (start_date > end_date) {...}

回答by The Alpha

If this is always in this format (yyyy-mm-dd/2013-01-01) then you can compare as string

如果这始终是这种格式 ( yyyy-mm-dd/2013-01-01),那么您可以将其作为字符串进行比较

var d1 = '2013-11-01', d2 = '2013-11-02';
console.log(d1 < d2); // true
//console.log(d1.getFullYear()); won't work, not date object

See Lexicographical order

参见词典顺序

An important exploitation of lexicographical ordering is expressed in the ISO 8601 date formatting scheme, which expresses a date as YYYY-MM-DD. This date ordering lends itself to straightforward computerized sorting of dates such that the sorting algorithm does not need to treat the numeric parts of the date string any differently from a string of non-numeric characters, and the dates will be sorted into chronological order. Note, however, that for this to work, there must always be four digits for the year, two for the month, and two for the day

ISO 8601 日期格式方案表达了对字典顺序的一个重要利用,该方案将日期表示为 YYYY-MM-DD。这种日期排序有助于对日期进行直接的计算机化排序,因此排序算法不需要将日期字符串的数字部分与非数字字符的字符串区别对待,并且日期将按时间顺序排序。但是请注意,要使其正常工作,年份必须始终为四位数,月份为两位数,日为两位数

But, you can use this to compare dates

但是,您可以使用它来比较日期

var d1 = new Date("11-01-2013");
var d2 = new Date("11-04-2013");
console.log(d1);
console.log(d1.getMonth()); // 10 (0-11)
console.log(d1.getFullYear()); // 2013
console.log(d1.getDate()); // 1
console.log(d1 < d2); // true

Check this fiddle.

检查这个小提琴

回答by Rahul Tripathi

You may try like this:

你可以这样尝试:

var d1 = Date.parse("2013-11-01");
var d2 = Date.parse("2013-11-04");
if (d1 < d2)

Also check out Date.parseand Compare dates with JavaScript

另请查看Date.parse使用 JavaScript 比较日期

回答by Arnaldo Capo

Try using a timestamp.

尝试使用时间戳。

var date1 = +new Date("2013-11-01");
var date2 = +new Date("2013-11-04");

console.log(date1);
console.log(date2);

console.log(date1>date2);