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โญ๐Ÿ™

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

๐Ÿ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay