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

1

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⭐🙏

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay