gpt4 book ai didi

javascript - 比较两个 JavaScript 字符串日期

转载 作者:行者123 更新时间:2023-12-01 01:56:18 25 4
gpt4 key购买 nike

如何比较以下两个日期?

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) {...}

最佳答案

如果始终采用这种格式(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

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

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 .

关于javascript - 比较两个 JavaScript 字符串日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19524577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com