添加天数并在 javascript 中创建一个函数

Add days and create a function in javascript

我正在开发一个从 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>
          }

有没有人有想法?

  { fiveDaysAgo < datePosted ?
          <Typography>
            New!
          </Typography> :
          <Typography>
            Old
          </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>
          }

您可以创建一个函数以所需的方式转换值。在这种情况下,您将 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 中的任何其他 JS 代码一样自由使用它 return:

const Component = ({ createdAt }) => {
  return (
    <>
      {!isOutdated(createdAt) && (
        <Typography>
          New!
        </Typography>  
      )}
    </>
  )
}