Home > OS >  Convert string to date format in JavaScript
Convert string to date format in JavaScript

Time:03-21

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

   

CodePudding user response:

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);

CodePudding user response:

There's no built-in method to convert date into your expected output although you can try this piece of code to convert date into your expected output;

var date = '2/3/2022 17:57:30'
var temp = new Date(date).toLocaleDateString().replaceAll("/","-");
  • Related