简体   繁体   English

更改日期字符串的格式

[英]Changing the format of a date string

I have a date string, 04-11-2010 , in JavaScript I want to have a function that will convert it to 2010-11-04 . 我在JavaScript中有一个日期字符串04-11-2010 ,我想要一个将其转换为2010-11-04的函数。

Does anyone know how I can do this? 有人知道我该怎么做吗?

JavaScript has a string split function, which separates a string into an array of parts. JavaScript具有字符串拆分功能,该功能可将字符串分成多个部分。 You can use slice to just chop up the parts of the string: 您可以使用slice来截断字符串的各个部分:

var str = "04-11-2010";

str = str.slice(-4) + "-" + str.slice(3, 5) + "-" + str.slice(0, 2);
alert(str);
//-> "2010-11-04"

Another solution is to split the string on the - character, swap the parts around and rejoin it. 另一个解决方案是在-字符上分割字符串,交换周围的部分,然后重新加入

var str = "04-11-2010",
    // Split the string into an array
    arr = str.split("-"),
    // Store the value of the 0th array element
    tmp = arr[0];

// Swap the 0th and 2nd element of the array
arr[0] = arr[2];
arr[2] = tmp;

// Rejoin the array into our string
str = arr.join("-");

alert(str);
//-> 2010-11-04

Top of my head: 我的头顶:

 var dt1   = parseInt(ab.substring(0,2),10);
 var mon1  = parseInt(ab.substring(3,5),10);
 var yr1   = parseInt(ab.substring(6,10),10);

Then you have the pieces you need. 然后,您便拥有了所需的零件。

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

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