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.
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.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With