我有一組包含時間戳的物件,我正在嘗試按升序對它們進行排序。我嘗試在排序時使用 moment 將它們轉換為 24 小時時間,還比較時間戳本身,但由于某種原因,我仍然以隨機順序獲取我的時間。有什么我想念的嗎?
已轉換 12 小時時間的資料
[{start: '9:04 AM', end: '9:34 AM'}, {start: '3:04 AM', end: '3:34 AM'}...]
const sortedAppointments = appointments.sort(
(a, b) => moment(a.start).format("H:mm") - moment(b.start).format("H:mm"),
);
注意:排序后,我在 UI 中映射陣列。但是這個排序函式的輸出仍然是亂序的“/
uj5u.com熱心網友回復:
以正確的格式將時間讀入 moment,然后比較 UNIX 時間戳。
const sortedAppointments = appointments.sort(
(a, b) => moment(a.start, "h:mm a").unix() - moment(b.start, "h:mm a").unix()
);
uj5u.com熱心網友回復:
對于它的價值,這是一個沒有 200 kb 下載的 moment.js 的版本
let appointments = [{
start: '9:04 AM',
end: '9:34 AM'
}, {
start: '9:04 PM',
end: '10:34 PM'
}, {
start: '3:04 AM',
end: '3:34 AM'
}]
const conv = time => {
let mer = time.split(" ")[1].toLowerCase(),
tm = time.split(" ")[0].split(":");
if (mer === "pm") tm[0] = tm[0] 12;
return tm.join('');
}
const sortedAppointments = appointments.sort(
(a, b) => conv(a.start) - conv(b.start)
);
console.log(sortedAppointments)
uj5u.com熱心網友回復:
這是最適合我的解決方案:
const sortedAppointments = appointments.sort(
(a, b) => moment(a.start).format("x") - moment(b.start).format("x"),
);
uj5u.com熱心網友回復:
var a = [['9:04 AM', '9:34 AM'], ['3:04 AM', '3:34 AM'], ['3:34 PM', '3:44 PM'],['1:24 PM', '3:34 PM']];
a.sort(sortFunction);
function sortFunction(a, b) {
//alert(2);
val1 = moment(a[0],["hh:mm A"]).format("HH:mm");
val2 = moment(b[0],["hh:mm A"]).format("HH:mm");
if (val1 === val2 ) {
return 0;
}
else {
return (val1 < val2) ? -1 : 1;
}
}
//document.getElementById("todaysdate").innerHTML = a;
for (i = 0; i < a.length; i )
document.writeln((i 1) ": " a[i] '<br>');
<html>
<head>
<title>MomentJS - Working Example</title>
<script type = "text/JavaScript" src = "https://MomentJS.com/downloads/moment.js"></script>
</head>
<body>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/459415.html
標籤:javascript 排序 时刻
