Changing the format of a date string
I have a date strin开发者_如何学编程g, 04-11-2010
, in JavaScript I want to have a function that will convert it to 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. You can use slice
to just chop up the parts of the string:
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.
精彩评论