我正在开发一个函数,从API调用得到的日期。准确地说,我正在做的是我试图抓住这个字段,例如
17/05/2022,在我的应用程序中为:
{new Date(job.created).toLocaleDateString()}
然而,我想做的基本上是把上面的减去5天。如果日期大于这个差值,那么就在h1上加上old
我有以下代码工作,并正确地注销我的日期:
const fiveDaysAgo = new Date(today - (5*days)).toLocaleDateString()
const datePosted = new Date(job.created).toLocaleDateString()
console.log('five days ago is', fiveDaysAgo)
console.log('date posted was', datePosted)
但是我想有条件地渲染,例如-
{ fiveDaysAgo < datePosted
<Typography>
New!
</Typography>
}
有人有什么想法吗?
您可以创建一个函数以所需的方式转换值。在本例中,您将snake_case
值转换为Capitalised Text
值。
const days = 1000 * 60 * 60 * 24;
const isOutdated = (date: Date): boolean => {
const nowStamp = new Date().getTime();
const dateStamp = date.getDate();
return nowStamp - dateStamp > 5 * days;
};
然后你可以自由地使用它作为JSX return中的任何其他JS代码:
const Component = ({ createdAt }) => {
return (
<>
{!isOutdated(createdAt) && (
<Typography>
New!
</Typography>
)}
</>
)
}
const fiveDaysAgo = new Date(today - (5*days)).toLocaleDateString()
const datePosted = new Date(job.created).toLocaleDateString()
console.log('five days ago is', fiveDaysAgo)
console.log('date posted was', datePosted)
//then compare timestamp
fiveDaysAgo = fiveDaysAgo.getTime();
datePosted = datePosted.getTime();
{ fiveDaysAgo < datePosted
<Typography>
New!
</Typography>
}