Reorder date using javascript

If I have a date, like 8/9/2010 in a text box, how is it possible to set the variable to 201098 as simple as possible?

Thanks in advance.

+3
source share
5 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 (if necessary), you can 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/

+8
source

I would recommend using Datejs to handle your dates.

You can do something like

date.toString("yyyyMMdd");

to get the date in the desired format

+1
source

'/', , , .

:

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

This is basically an idea that I think you are about to.

-Brian J. Stinar -

Dang, it looks like I was beaten before the blow ...

0
source

Using regex:

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

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

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

processDate("8/9/2010");

Easy to manage and debug, of course.

0
source

Source: https://habr.com/ru/post/1762680/


All Articles