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

Invalid Date with datejs

I need to convert string to date.

But I don’t understand why the end date is not converted from a string. Then I decided to use the daysJs library, but it gave the same thing

let date={
end:"15-10-2022",
start:"05-10-2022",
}
let range = {
        start:new Date(date.start),
        end: new Date(date.end),
};
      
console.log(range)

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

>Solution :

Running the code snippet embedded in Stack, I can see that your end property is null, presumably because the formattign for the dates is MM-DD-YYYY and you’re formatting them as DD-MM-YYYY. The simplest solution is to Swap your month and day in the date. Otherwise, just use MomentJS for its simplification of working with dates.

Formatting DD-MM-YYYY without moment:

let date = {
    end: '15-10-2022',
    start: '05-10-2022'
};
let range = {
    start: new Date(date.start.split('-').reverse().join('-')),
    end: new Date(date.end.split('-').reverse().join('-'))
};
console.log(range);

Formatting DD-MM-YYYY with moment:

let date = {
    end: '15-10-2022',
    start: '05-10-2022'
};
let range = {
    start: moment(date.start, 'DD-MM-YYYY'),
    end: moment(date.end, 'DD-MM-YYYY')
};
console.log(range);
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