All browsers
The most reliable way to format a date with the source format you're using, is to apply the following steps :
- Use your time string as input for
new Date()
- Use
.getDate()
, .getMonth()
and .getFullYear()
to get respectively the day, month and year
- Paste the pieces together according to your target format
The format
function below shows you the optimal way to combine those four steps :
var date = '2015-11-09T10:46:15.097Z';
function format(input) {
var date = new Date(input);
return [
("0" + date.getDate()).slice(-2),
("0" + (date.getMonth()+1)).slice(-2),
date.getFullYear()
].join('/');
}
document.body.innerHTML = format(date); // OUTPUT : 09/11/2015
(See also this Fiddle).
Note
While this approach does work in all browsers, you'll need an additional step before new Date(input)
to parse your ISO 8601 format if you need to support browsers as old as IE8--. See the accepted answer at Javascript JSON Date parse in IE7/IE8 returns NaN for a function that does exactly that.
Modern browsers only
You can also use the built-in .toLocaleDateString
method to do the formatting for you. You just need pass along the proper locale and options to match the right format, which unfortunately is only supported by modern browsers (*) :
var date = '2015-11-09T10:46:15.097Z';
function format(input) {
return new Date(input).toLocaleDateString('en-GB', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
});
}
document.body.innerHTML = format(date); // OUTPUT : 09/11/2015
(See also this Fiddle).
(*) According to the MDN, "Modern browsers" means Chrome 24+, Firefox 29+, IE11, Edge12+, Opera 15+ & Safari nightly build