-
阿晨1998
您可以moment像这样简单地使用 的内置比较器this.state.data.filter(item => moment(item.publishedDate,'DD/MM/YYYY').isSameOrAfter(today))
-
米脂
构造函数Date不会接受您当前使用的格式,但它会识别MM/DD/YYYY格式。此外,filter保留函数返回 true 的元素,因此您应该检查 是否Date小于或等于当前Date。const today = new Date;this.state.data = this.state.data.filter(({publishedDate})=>{ const [d, m, y] = publishedDate.split("/"); return new Date(m + "/" + d + "/" + y) <= today;});
-
慕田峪4524236
使用 moment 的String + Format 初始值设定项和Is Same Or After:this.state.data.filter(item => moment(item.publishedDate, 'DD/MM/YYYY').isSameOrAfter())
-
狐的传说
一种可能性是使用辅助函数notAfterToday,它接受一个属性名称(在我们的例子中'publishedDate')并返回一个函数,该函数接受具有该属性名称的对象并报告该日期是在当前日期之前还是在当前日期。例如,它通过将 2020 年 12 月 18 日转换为“20201218”,并使用该字符串进行比较来实现此目的。请注意,这样做的一个优点是它只调用一次 Date 构造函数,用于初始计算今天的日期。const data = [{publishedDate: '18/12/2020', Url: 'http://example.com/1', Title: 'abc'}, {publishedDate: '19/01/2021', Url: 'http://example.com/2', Title: 'def'}, {publishedDate: '07/04/2014', Url: 'http://example.com/3', Title: 'ghi'}, {publishedDate: '19/07/2023', Url: 'http://example.com/4', Title: 'jkl'}, {publishedDate: '05/01/1966', Url: 'http://example.com/5', Title: 'mno'}, {publishedDate: '01/07/2041', Url: 'http://example.com/6', Title: 'pqr'}, {publishedDate: '08/05/2061', Url: 'http://example.com/7', Title: 'stu'}, {publishedDate: '10/08/1999', Url: 'http://example.com/8', Title: 'vwx'}]const notAfterToday = (prop) => { const reorg = (date, [d, m, y] = date.split('/')) => y + m + d const today = new Date() const compare = today .getFullYear() + String ((today .getMonth () + 1)) .padStart (2, '0') + String (today .getDate ()) .padStart (2, '0') return (d) => compare >= reorg (d [prop])}console .log (data .filter (notAfterToday ('publishedDate'))).as-console-wrapper {max-height: 100% !important; top: 0}
-
不负相思意
在与今天进行比较之前,您必须对日期字符串进行一些微调。你可以试试这个——const data = [ { publishedDate: "19/01/2021", url: '', title: 'date1' }, { publishedDate: "19/05/2021", url: '', title: 'date2' }, { publishedDate: "13/01/2020", url: '', title: 'date3' }, { publishedDate: "16/09/2009", url: '', title: 'date4' },];const parseDate = (dateString) => new Date(...dateString.split('/').reverse());const result = data.filter(item => parseDate(item.publishedDate) <= new Date());console.log(result);
-
拉莫斯之舞
将日期存储为字符串是一种代码味道。与将它们存储为 JS 原生日期格式或 Moment.JS 日期对象等替代方案相比,比较、存储和转换它们更加困难。这是一个简单的示例,说明如果您将对象存储为日期,您可以如何做到这一点。请注意,第三个对象已被过滤掉。const myObject1 = { publishedDate: new Date("2019-01-01"), // NEW Url: "whatever", Title: "sample",}const myObject2 = { publishedDate: new Date("2020-01-01"), // NEW Url: "whatever", Title: "sample",}const myObject3 = { publishedDate: new Date("2099-01-01"), // NEW Url: "whatever", Title: "sample",}const arr = [myObject1, myObject2, myObject3];const today = new Date();const filtered = arr.filter((obj) => obj.publishedDate < today);console.log(filtered);