Skip to content

Convert string to date format in JavaScript

I have a string variable I want the variable into date format.

My Code:

var date = '2/3/2022 17:57:30'
var temp = new Date(date)

My Output:

2022-02-03T17:57:30.000Z

Expected Output:

2022-02-03

   

Answer

You can use toLocaleDateString with an argument that specifies a locale for which your format is used. For instance, the Swedisch locale uses the YYYY-MM-DD format:

var date = '2/3/2022 17:57:30'
var temp = new Date(date).toLocaleDateString("se");
console.log(temp);