我从excel工作表得到输入,日期不是正确的ISO格式,可以操作,即,列看起来像下面,我试图排序它使用转换到正确的日期使用javascript日期和时刻,但我没有得到正确的输出,我可以使用第二个意见对这件事。
>
我写的方法 我从上面的方法得到的输出是dateCompare = (d1, d2) => {
let d1Component = d1.toString().split('/')
, d2Component = d2.toString().split('/')
, rD1 = new Date(parseInt(20 + d1Component[2]), d1Component[1] - 1, d1Component[0])
, rD2 = new Date(parseInt(20 + d2Component[2]), d2Component[1] - 1, d2Component[0])
return moment(rD1).isAfter(moment(rD2))
}
[30/09/35“,”28/02/23“,”31/05/21“,”31/12/21“,”31/10/22“,”30/09/21“,”30/09/20“,”30/05/22“,”30/09/20“,”30/05/22“,”30/04/21“,”30/06/21“,”30/02/22“,”31/12/22“,”30/06/21“,”28/02/22“,”31/12/22“,”30/06/22“,”30/06/22“,”30/04/22“,”31/10/20“,”31/08/22“,”31/08/22“,”
比较函数应该返回负数表示小于,正数表示大于,
function dateCompare(d1, d2) {
const d1Parsed = moment(d1, "DD/MM/YY");
const d2Parsed = moment(d2, "DD/MM/YY");
if (d1Parsed.isBefore(d2Parsed)) {
return -1;
} else if (d1Parsed.isSame(d2Parsed)) {
return 0;
} else {
return 1;
}
}
或者,取它们的时间戳的差值(如果
function dateCompare(d1, d2) {
const d1Parsed = moment(d1, "DD/MM/YY");
const d2Parsed = moment(d2, "DD/MM/YY");
return d1Parsed.valueOf() - d2Parsed.valueOf();
}
您可以使用映射和转换日期,而不是对它们进行排序。
null
const dates = ["28/02/23", "31/12/21", "31/05/21", "30/09/23", "31/10/22", "30/09/21", "30/06/23", "31/05/22", "30/04/21", "31/07/21", "30/06/21", "28/02/22", "31/12/22", "30/06/22", "31/08/21", "30/04/22", "31/10/20", "31/08/22", "31/07/22", "31/05/23", "31/01/23", "30/04/23", "30/09/22", "28/02/21", "30/11/20", "30/11/21", "31/01/21", "31/03/23", "31/01/22", "31/07/23", "31/12/20", "31/03/21", "31/08/23", "30/11/22", "31/10/21", "31/03/22", "30/09/20"];
const convertedDates = dates.map(d => {
var day = d.split("/")[0];
var month = d.split("/")[1];
var year = d.split("/")[2];
return "20" + year + '-' + ("0" + month).slice(-2) + '-' + ("0" + day).slice(-2);
})
.sort();
;
console.log(convertedDates);