[英]Categorize array by date using moment.js
我正在尝试按日期对数组项进行分组。 数组列表如下所示:
{
title: 'title 01',
timestamp: 1574082000000
},
{
title: 'title 02',
timestamp: 1574071200000
},
{
title: 'title 03',
timestamp: 1573974000000
},
.
.
.
output 应该是这样的:
2019 年 11 月 19 日(或今天)
标题 01
标题 02
2019 年 11 月 18 日
标题 03
上周
标题 04
九月
标题...
坦率地说,我不能做太多,但我设法使用以下代码以所需格式获取周名称:
for ( let i = 0; i < transactions.length; i++ ) {
let timestamps = moment( transactions[i].timestamp ).startOf('week')._d
let weeklyTime = moment( timestamps ).format( 'Do MMMM, YYYY' )
console.log( weeklyTime )
}
最好的,
~弥敦道。
也许来自 moment.js 的“相对时间”是您正在寻找的? .fromNow()
方法为您提供了一个不错的相对日期。
var transactions=[{ title: 'title 01', timestamp: moment().subtract(2, 'hours') //create test date for 2 days ago }, { title: 'title 02', timestamp: moment().subtract(2, 'hours') //create test date for 2 days ago }, { title: 'title 03', timestamp: moment().subtract(1, 'days') //create test date for yesterday }, { title: 'title 04', timestamp: moment().subtract(7, 'days') //create test date for last week }, { title: 'title 05', timestamp: moment().subtract(70, 'days') //create test date for 2 months ago }] var transactionsSortedWithRelativeTime = transactions.sort((t1, t2) => t1.valueOf()-t2.valueOf()).map(t => ({...t, when:moment(t.timestamp).fromNow()})); (new Set(transactionsSortedWithRelativeTime.map(t => t.when))).forEach(when => { console.log(when + ': '); transactionsSortedWithRelativeTime.filter(t => t.when == when).forEach(t => console.log(' ' + t.title)) })
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.