Shu Rahman
Shu Rahman

Reputation: 792

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

   

Upvotes: 0

Views: 540

Answers (2)

trincot
trincot

Reputation: 349956

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

Upvotes: 1

Abbas Shaikh
Abbas Shaikh

Reputation: 324

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("/","-");

Upvotes: 1

Related Questions