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.
This question is related to
javascript
jquery
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');_x000D_
alert(((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear());
_x000D_
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) {_x000D_
var year = date.getFullYear();_x000D_
_x000D_
var month = (1 + date.getMonth()).toString();_x000D_
month = month.length > 1 ? month : '0' + month;_x000D_
_x000D_
var day = date.getDate().toString();_x000D_
day = day.length > 1 ? day : '0' + day;_x000D_
_x000D_
return month + '/' + day + '/' + year;_x000D_
}
_x000D_
Update for ES2017 using String.padStart(), supported by all major browsers except IE.
function getFormattedDate(date) {_x000D_
let year = date.getFullYear();_x000D_
let month = (1 + date.getMonth()).toString().padStart(2, '0');_x000D_
let day = date.getDate().toString().padStart(2, '0');_x000D_
_x000D_
return month + '/' + day + '/' + year;_x000D_
}
_x000D_
If your dateString is RFC282 and ISO8601 compliant:
pass your string into the Date Constructor:
const dateString = "2020-10-30T12:52:27+05:30"; // ISO8601 compliant dateString
const D = new Date(dateString); // {object Date}
from here you can extract the desired values by using Date Getters:
D.getMonth() + 1 // 10 (PS: +1 since Month is 0-based)
D.getDate() // 30
D.getFullYear() // 2020
If you use a non standard date string:
destructure the string into known parts, and than pass the variables to the Date Constructor:
new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])
const dateString = "30/10/2020 12:52:27";
const [d, M, y, h, m, s] = dateString.match(/\d+/g);
// PS: M-1 since Month is 0-based
const D = new Date(y, M-1, d, h, m, s); // {object Date}
D.getMonth() + 1 // 10 (PS: +1 since Month is 0-based)
D.getDate() // 30
D.getFullYear() // 2020
Source: Stackoverflow.com