gpt4 book ai didi

javascript - 如何在 JavaScript 中使用 'MMMM Do YYYY, h:mm:ss am/pm' 对日期进行排序

转载 作者:行者123 更新时间:2023-12-03 02:35:15 25 4
gpt4 key购买 nike

var array = [{ 
id: 1,
date: 'Mar 12 2017 10:00:00 am'
},{
id: 2,
date: 'Mar 12 2017 08:00:00 pm'
},{
id: 3,
date: 'Mar 12 2017 05:00:00 am'
},{
id: 4,
date: 'Mar 18 2017 09:00:00 am'
}];

这是我的逻辑:-

sortedPatients = PatientsListArray.sort((a, b) => {
if (b.Date < a.Date) return -1
if (b.Date > a.Date) return 1
})

我得到这样的输出 id4 , id1 , id2 , id3

我期望这样的输出id4, id2, id3, id1

有人可以帮助我吗?

最佳答案

您的代码有一些问题:

您正在比较字符串而不是日期对象,因此,您正在对字符串进行排序:-)

if (b.Date < a.Date) return -1
^ ^

您将使用大写的 Date 属性获取日期字符串。

if (b.Date < a.Date) return -1
^ ^

您的期望不正确,因为您想要获得降序结果id4, id2, id1, id3

id4, id2, id3, id1
^ ^
->
<-

您的源数组包含无效的日期属性值,因此您需要用引号将其括起来 "

date: Mar 12 2017   10:00:00 am
^ ^

您可以使用 new Date() 构造函数或静态函数 Date.parse (获取自 1970 年 1 月 1 日 00:00:00 以来的毫秒数世界标准时间)。

new Date()

String value representing a date. The string should be in a format recognized by the Date.parse() method (IETF-compliant RFC 2822 timestamps and also a version of ISO8601).

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local. Reference

<小时/>

Date.parse()

The parse() method takes a date string (such as "Dec 25, 1995") and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the setTime() method and the Date object. Reference

查看包含这些修复的代码片段:

var array = [{
id: 1,
date: 'Mar 12 2017 10: 00: 00 am'
}, {
id: 2,
date: 'Mar 12 2017 08: 00: 00 pm'
}, {
id: 3,
date: 'Mar 12 2017 05: 00: 00 am'
}, {
id: 4,
date: 'Mar 18 2017 09: 00: 00 am'
}];

var sorted = array.sort((a, b) => {
//The parse function will convert those strings to Dates.
var bdt = Date.parse(b.date);
var adt = Date.parse(a.date);
return bdt > adt ? 1 : (bdt < adt ? -1 : 0);
});

console.log(sorted);

看到了吗?现在你的逻辑开始工作了!

关于javascript - 如何在 JavaScript 中使用 'MMMM Do YYYY, h:mm:ss am/pm' 对日期进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48560820/

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