简体   繁体   中英

How can I get date range using dayjs?

I want to tell if a random day is in 7 days from now on . I know there is isBetween function, but I want to solve this problem only using diff . when I run the code below, this error occurred.

Operator '>' cannot be applied to types 'boolean' and 'number'.(2365)

Here is my code

import * as React from 'react';
import dayjs from 'dayjs';
import './style.css';

export default function App() {
  const randomDay = dayjs('2022-09-15');
  const today = dayjs('2022-09-12');
  return (
    <div>{ 0 < randomDay.diff(today, 'day') < 7 && <h1>Today is later</h1>}</div>
  );
}

What is the problem? And how can I solve it?

You cannot do two comparisions at once.

const diff = randomDay.diff(today, 'day');

...

0 <  diff && diff < 7

You can do this by using the second argument in diff function.

const dayJS = require('dayjs')

const randomDay = dayJS('2022-09-15')
const today = dayJS('2022-09-12')

const difference = randomDay.diff(today, 'days')

console.log(difference) // 3 days

console.log(difference > 7 ? 'After Seven days' : 'Less than 7 days')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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