Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if given date is in last 3 weeks

I have a sample date:

const date = '10-03-2022';

I need to check if this date is longer than 3 weeks or not. Or speaking differently – I need to check if this date is in the last 3 weeks or older.

I was trying with date-fns but its not the result I expect.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { formatDistance, subWeeks } from 'date-fns'

formatDistance(subWeeks(new Date(), 3), date)

I dont have to be honest any idea how to deal with such problem. Thats why I wanted to ask you here for help. Thanks!

>Solution :

You can use isAfter to compare against subWeeks. This will return true even if the date is in the future from now.

Alternatively you can use isWithinInterval to test if the date is within the period between now and three weeks before now. (not included in the cdn version available).

const dateIsWithinInterval = isWithinInterval(testDate,
    { start: subWeeks(new Date(), 3), end: new Date() })

You’ll still need to parse your string into a valid Date object.

//import { isAfter, subWeeks } from 'date-fns';
const { isAfter, subWeeks } = dateFns; // cdn assignment

const dateString = '10-06-2022';
const [d, m, y] = dateString.split('-').map(n => parseInt(n, 10));
// months are 0 indexed so you need to subrtract 1.
const testDate = new Date(y, m - 1, d);

const dateIsAfter = isAfter(testDate, subWeeks(new Date(), 3));

console.log('isAfter:', dateIsAfter);
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/2.0.0-alpha0/date_fns.min.js" integrity="sha512-0kon+2zxkK5yhflwFqaTaIhLVDKGVH0YH/jm8P8Bab/4EOgC/n7gWyy7WE4EXrfPOVDeNdaebiAng0nsfeFd9A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading