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; }
Ore4444 Apr 02 '13 at 12:59 on 2013-04-02 12:59
source share