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 when trying to change the date format

I have a date value and want to format it.

This is the value:

Thu Jul 07 2022 01:03:18 GMT+0200 (Mitteleuropäische Sommerzeit) 

I want to make this format:

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

console.log(new Date('YYYY-MM-DD h:i:s', dateVal));

but I get invalid date.

How can I make it right ?

>Solution :

Though the Date object’s constructor accepts a handful of parameters to set an actual date, there is no parameter to specify in what way the date should be presented.

So:

let dateVal="Thu Jul 07 2022 01:03:18 GMT+0200 (Mitteleuropäische Sommerzeit)";
console.log(new Date('YYYY-MM-DD h:i:s', dateVal));

is nonsense as it tries to construct a date from two strings.

What you can do however is call the Date’s built-in function .toLocaleString() including the "sv" locale to get your Date formatted in YYYY-MM-DD h:m:s format.

For example:

let dateVal = "Thu Jul 7 2022 01:03:18 GMT+0200 (Mitteleuropäische Sommerzeit)";
console.log(new Date(dateVal).toLocaleString("sv"));
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