Format date to MM/dd/yyyy in JavaScript [duplicate]

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

Answers:

Answer

Try this; bear in mind that JavaScript months are 0-indexed, whilst days are 1-indexed.

var date = new Date('2010-10-11T00:00:00+05:30');
alert(((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear());
Answer

All other answers don't quite solve the issue. They print the date formatted as mm/dd/yyyy but the question was regarding MM/dd/yyyy. Notice the subtle difference? MM indicates that a leading zero must pad the month if the month is a single digit, thus having it always be a double digit number.

i.e. whereas mm/dd would be 3/31, MM/dd would be 03/31.

I've created a simple function to achieve this. Notice that the same padding is applied not only to the month but also to the day of the month, which in fact makes this 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;
}


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;
}

Answer

Pass your string into the Date Object:

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

from here you can extract the desired using the following methods:

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

Note that getMonth() returns the month number zero based (0-11) therefore a +1 is needed.

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


Another way, using .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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.