Cleaner way to convert dd-mm-yyyy to mm-dd-yyyy format in Javascript

I have this date as a line with me 07/15/2011, which is in the format dd-mm-yyyy. I needed to create an object Datefrom this line. So I need to convert the date in format dd-mm-yyyyto mm-dd-yyyy.

I did the following.

var myDate = '15-07-2011';
var chunks = myDate.split('-');

var formattedDate = chunks[1]+'-'+chunks[0]+'-'+chunks[2];

Now I got the line 07-15-2011, which is in the format mm-dd-yyyy, and I can pass it to the constructor Date()to create the object Date. I want to know if there is a cleaner way to do this.

+5
source share
9 answers

It looks very clean as it is.

+5
source

- "" .

, (, , , , ?), DateJS, Javascript.

+2

,

var myDate = '15-07-2011';
var chunks = myDate.split('-');
var formattedDate = [chunks[1],chunks[0],chunks[2]].join("-");

- , , .

+1
var formattedDate = chunks[1] + '-' + chunks[0] + '-' + chunks.pop();
+1

, .

var date = '15-07-2011'.split('-');
date = date[1]+'-'+date[0]+'-'+date[2];

var date = '15-07-2011'.replace(/(\d*)-(\d*)-(\d*)/,'$2-$1-$3')
+1
var c = '01-01-2011'.split('-');
var d = new Date(c[2],c[1]-1,c[0]);
+1

, , - :

var myDate = '15-07-2011';
myDate.split('-').reverse().join('-');

Gives you "2011-07-15", which, although not quite what you requested, will be correctly analyzed Date

0
source

I wrote a library for parsing, managing and formatting strings called Moment.js

var date = moment('15-07-2011', 'DD-MM-YYYY').format('DD-MM-YYYY');
0
source

Try

myDate.format("mm-dd-yyyy");
-2
source

All Articles