简体   繁体   English

在 JavaScript 中将字符串转换为日期格式

[英]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:我的 Output:

2022-02-03T17:57:30.000Z

Expected Output :预计 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;没有内置方法可以将日期转换为您期望的 output,尽管您可以尝试使用这段代码将日期转换为您期望的 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.您可以将toLocaleDateString与指定使用您的格式的语言环境的参数一起使用。 For instance, the Swedisch locale uses the YYYY-MM-DD format:例如,瑞典语言环境使用 YYYY-MM-DD 格式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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