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;
};

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);
        });
    });

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


Shared with from Codever. 👉 Use the Copy to mine functionality to copy this snippet to your own personal collection and easy manage your code snippets.

Codever is open source on Github ⭐🙏

Subscribe to our newsletter for more code resources and news

Adrian Matei (aka adixchen)

Adrian Matei (aka adixchen)
Life force expressing itself as a coding capable human being

routerLink with query params in Angular html template

routerLink with query params in Angular html template code snippet Continue reading