简体   繁体   中英

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

I have this date as string with me 15-07-2011 which is in the format dd-mm-yyyy . I needed to create a Date object from this string. So I have to convert the date in dd-mm-yyyy to mm-dd-yyyy format.

What I did is the following.

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

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

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

That looks very clean as it is.

Re-arranging chunks of a string is a perfectly "clean" and legitimate way to change a date format.

However, if you're not happy with that (maybe you want to know that the string you're re-arranging is actually a valid date?), then I recommend you look at DateJS , which is a full-featured date handling library for Javascript.

Depends what you mean by cleaner

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

Some would say this is cleaner, but it does essentially the same.

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

If you wanted to you could cut down on some variables.

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

If you want a one liner

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

I'll add my opinion that your solution is perfectly valid, but if you want something different:

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

Will give you '2011-07-15' which, although not exactly what you asked for, will be parsed properly by Date

I wrote a library for parsing, manipulating, and formatting strings named Moment.js

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

Try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM