开发者

Change order in a date with javascript

If I hav开发者_Python百科e a date like 8/9/2010 in a textbox, how can I easiest set a variable to the value 201098?

Thanks in advance.


var date = "8/9/2010";

var result = date.split('/').reverse().join('');

EXAMPLE: http://jsfiddle.net/hX357/

To add leading zeros to the month and day (when needed) you could do this:

var date = "8/9/2010";

var result = date.split('/');

for( var i = 2; i--; )
    result[i] = ("0" + result[i]).slice(-2);

result = result.reverse().join('');

EXAMPLE: http://jsfiddle.net/hX357/2/


I would recommend using Datejs to process your dates.

You can do something like

date.toString("yyyyMMdd");

to get the date in the format you want


Using regex:

"8/9/2010".replace(/([0-9]+)\/([0-9]+)\/([0-9]+)/,"$3$2$1")


Do a split on '/', take the last element and make it the first of a new string, the middle element becomes the middle element of the new string, and the first element becomes the last element of a new string.

It would be like this:

myString = document.getElementById('date_textbox').value; var mySplitResult = myString.split("\"); var newString = mySplitResult[2] + mySplitResult[1] + mySplitResult[0];

This is basically the idea I think you are going for.

-Brian J. Stinar-

Dang, it looks like I was beaten to the punch...


Or you can use the built-in JavaScript Date class:

function processDate(dStr) {
    var d = new Date(dStr);
    return d.getFullYear() + (d.getMonth() + 1) + d.getDate();
}

processDate("8/9/2010");

Easiest to manage and debug, certainly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜