DEV Community

Cover image for How to compare date (no time) with current day in javascript
Adrian Matei for Codever

Posted on • Originally published at codever.dev

How to compare date (no time) with current day in javascript

Get current date with new Date() and setHours to 0, 0, 0 and then you are ready to compare with the input date, which is a string in the yyyy-MM-dd format

export const isLessThanToday = (input: string): boolean => { //format of input date is YYYY-MM-DD const today = new Date(); today.setHours(0, 0, 0); return notEmpty(input) && new Date(input) < today; }; 
Enter fullscreen mode Exit fullscreen mode

To test that we can use the following jest test:

 describe('isLessThanToday > ', () => { test.each([ [null, false], [undefined, false], ['AXON', false], ['1900-01-01', true], ['2099-12-12', false], // TODO change this date when in 2099 :) [new Date().toISOString().slice(0, 10), false], //today [new Date(new Date().setDate(new Date().getDate() - 1)).toISOString().slice(0, 10), true], //yesterday [new Date(new Date().setDate(new Date().getDate() - 7)).toISOString().slice(0, 10), true], //one week ago ])('given input date %p, it should return %p', (input, expected) => { expect(isLessThanToday(input)).toEqual(expected); }); }); 
Enter fullscreen mode Exit fullscreen mode

See this How to use jest test.each function to understand the usage of test.each function


Shared with ❤️ from Codever. Use 👉 copy to mine functionality to add it to your personal snippets collection.

Codever is open source on Github⭐🙏

Top comments (0)