Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change order in a date with javascript

Tags:

javascript

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.

like image 726
Peter Avatar asked Dec 28 '22 08:12

Peter


2 Answers

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/

like image 147
user113716 Avatar answered Dec 31 '22 00:12

user113716


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

like image 42
Tarski Avatar answered Dec 31 '22 01:12

Tarski