Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 723
Sparky Avatar asked Jul 13 '11 18:07

Sparky


People also ask

How do you change date format from yyyy-mm-dd to dd mm yyyy JS?

Re: convert Date from YYYY-MM-DD to MM/DD/YYYY in jQuery/JavaScript. var tempDate = new Date("2021-09-21"); var formattedDate = [tempDate. getMonth() + 1, tempDate. getDate(), tempDate.

How convert dd mm yyyy string to date in JavaScript?

To convert a dd/mm/yyyy string to a date:Split the string on each forward slash to get the day, month and year. Pass the year, month minus 1 and the day to the Date() constructor. The Date() constructor creates and returns a new Date object.

What date format is dd mm yyyy in JavaScript?

To format a date as dd/mm/yyyy:Use the getDate() , getMonth() and getFullYear() methods to get the day, month and year of the date. Add a leading zero to the day and month digits if the value is less than 10 .


2 Answers

That looks very clean as it is.

like image 154
Paul Sonier Avatar answered Oct 28 '22 09:10

Paul Sonier


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.

like image 34
Spudley Avatar answered Oct 28 '22 11:10

Spudley