简体   繁体   English

使用 moment.js 按日期对数组进行分类

[英]Categorize array by date using moment.js

I'm trying to group the array items by date.我正在尝试按日期对数组项进行分组。 Array list looks like this:数组列表如下所示:

{
    title: 'title 01',
    timestamp: 1574082000000
},
{
    title: 'title 02',
    timestamp: 1574071200000
},
{
    title: 'title 03',
    timestamp: 1573974000000
},
.
.
.

The output should be like this: output 应该是这样的:

November 19, 2019 ( or today ) 2019 年 11 月 19 日(或今天)

Title 01标题 01

Title 02标题 02

November 18, 2019 2019 年 11 月 18 日

Title 03标题 03

Last Week上周

Title 04标题 04

September九月

Title...标题...

Frankly, I couldn't do too much but I manage to get the week names in the desired format with the following code:坦率地说,我不能做太多,但我设法使用以下代码以所需格式获取周名称:

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

Best,最好的,

~ Nathan. ~弥敦道。

Maybe "relative time" from moment.js is what you are looking for?也许来自 moment.js 的“相对时间”是您正在寻找的? .fromNow() method gives you a nice relative date. .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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM