Date format for MM / dd / yyyy in JavaScript

I have a date format similar to this '2010-10-11T00:00:00+05:30' . I need to format in MM/dd/yyyy using JavaScript or jQuery. Someone help me do the same.

+124
javascript jquery
Jul 21 '12 at 11:41
source share
3 answers

Try it; remember that JavaScript months are indexed 0 and days 1 are indexed.

 var date = new Date('2010-10-11T00:00:00+05:30'); alert((date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear()); 
+246
Jul 21 '12 at 11:48
source share

All other answers do not completely solve the problem. They print the date in the format mm / dd / yyyy, but the question was about MM / dd / yyyy. Notice the subtle difference? MM indicates that the leading zero should complement the month if the month is a single digit, so it should always be a two-digit number.

that is, if mm / dd is 3/31, MM / dd is 03/31.

I created a simple function to achieve this. Note that the same padding applies not only to the month, but also to the day of the month, which actually does it MM / DD / yyyy:

 function getFormattedDate(date) { var year = date.getFullYear(); var month = (1 + date.getMonth()).toString(); month = month.length > 1 ? month : '0' + month; var day = date.getDate().toString(); day = day.length > 1 ? day : '0' + day; return month + '/' + day + '/' + year; } 



An update for ES2017 using String.padStart (), supported by all major browsers except IE.

 function getFormattedDate(date) { let year = date.getFullYear(); let month = (1 + date.getMonth()).toString().padStart(2, '0'); let day = date.getDate().toString().padStart(2, '0'); return month + '/' + day + '/' + year; } 
+136
Apr 02 '13 at 12:59 on
source share

You can: .slice() and .split()

 var d = "2010-10-30T00:00:00+05:30".slice(0, 10).split('-'); d[1] +'/'+ d[2] +'/'+ d[0]; // 10/30/2010 


... or pass your string to a Date Object :

 var d = new Date("2010-10-30T00:00:00+05:30"); 

from here you can extract what you need using the following methods:

 d.getMonth()+1 // 10 d.getDate() // 30 d.getFullYear() // 2010 

Note that getMonth() returns the zero month number (0-11), so +1 is required.

Here you can find a list of other getters : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

+31
Jul 21 '12 at 12:15
source share



All Articles