简体   繁体   中英

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

   

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM