tags:

views:

45

answers:

5

Hi,

If I have a date like 8/9/2010 in a textbox, how can I easiest set a variable to the value 201098?

Thanks in advance.

+8  A: 
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/

patrick dw
+1 nice solution
Anurag
+1 for the simplest route
Nick Craver
I thought of this, but for some reason the back of my mind told me IE didn't support *Array.prototype.reverse*. Probably just confusing this with the other dozen Array functions that IE doesn't support. +1.
Andy E
+1  A: 

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

Tarski
A: 

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...

Brian Stinar
A: 

Using regex:

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

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.

palswim