Reputation: 2378
I have this date:
2015-05-28T23:00:00.000Z
I need to convert it to the local date which would be (in this format):
29/05/2015
I would expect the above formatted date to be correct based on the date string above.
How would I do this?
Thank you
Upvotes: 0
Views: 72
Reputation: 147503
It's been well covered elsewhere that using the Date constructor to parse strings isn't a good idea. The format in the OP is consistent with ES5 and will be parsed correctly by modern browsers, but not IE 8 which still has a significant user share.
Parsing the string manually isn't difficult:
function isoStringToDate(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5], b[6]));
}
Then to format it:
function dateToDMY(d) {
function z(n){return (n<10?'0':'') + n}
return z(d.getDate()) + '/' + z(d.getMonth()+1) + '/' + d.getFullYear();
}
console.log(dateToDMY(isoStringToDate('2015-05-28T23:00:00.000Z'))); // 29/05/2015
To be consistent with ES5, the parse function should check values aren't out of range but if you're confident of the correctness of the string that shouldn't be necessary.
Upvotes: 1
Reputation: 31
Please add the following code in script
<script>
var d = new Date("2015-05-28T23:00:00.000Z");
var str=d.toString();
var date = new Date(str),
mnth = ("0" + (date.getMonth()+1)).slice(-2),
day = ("0" + date.getDate()).slice(-2);
var local_date=[ date.getFullYear(), mnth, day ].join("/"); //yyyy/mm/dd
</script>
Hope it works.Thank you
Upvotes: 0
Reputation: 2378
Thank you for your replies.
I've got it formatted by doing:
var d = new Date('2015-05-28T23:00:00.000Z');
var n = d.getDate() + '/' + (d.getMonth() +1 ) + '/' + d.getFullYear();
document.getElementById("demo").innerHTML = n;
Upvotes: 0
Reputation: 2599
convert it to Date object:
var dateString = '2015-05-28T23:00:00.000Z';
var date = new Date(dateString)
then you cant format it:
var formatedDate = date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
But you can also use moment.js
moment(dateString).format('DD/MM/YYYY');
Upvotes: 1