Jefsama Jefsama - 3 months ago 14
Javascript Question

Javascript formatting array of dates

I have this array...

var dates = [{"date_play":"2016-08-22 00:00:00"},{"date_play":"2016-08-23 00:00:00"},{"date_play":"2016-08-24 00:00:00"}];


How can i format that date to produce like this:

var newDates = ['08-22-2016','08-23-2016','08-24-2016'];

Answer

Given that you already have text, you can just manipulate the text.

var dates = [{"date_play":"2016-08-22 00:00:00"},{"date_play":"2016-08-23 00:00:00"},{"date_play":"2016-08-24 00:00:00"}];

var newDates = [];
$.each(dates,function(i,obj){
    newDates.push(obj['date_play'].replace(/(\d{4})-(\d\d)-(\d\d).*$/,'$2-$3-$1'));
});
console.log(newDates);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Or:

var dates = [{"date_play":"2016-08-22 00:00:00"},{"date_play":"2016-08-23 00:00:00"},{"date_play":"2016-08-24 00:00:00"}];

var newDates = [];
dates.forEach(function(obj){
    newDates.push(obj['date_play'].replace(/(\d{4})-(\d\d)-(\d\d).*$/,'$2-$3-$1'));
});
console.log(newDates);

Or:

var dates = [{"date_play":"2016-08-22 00:00:00"},{"date_play":"2016-08-23 00:00:00"},{"date_play":"2016-08-24 00:00:00"}];

var newDates = dates.map(function(obj){
    return obj['date_play'].replace(/(\d{4})-(\d\d)-(\d\d).*$/,'$2-$3-$1');
});
console.log(newDates);

Or:

var dates = [{"date_play":"2016-08-22 00:00:00"},{"date_play":"2016-08-23 00:00:00"},{"date_play":"2016-08-24 00:00:00"}];

var newDates = dates.map(function(obj){
    var tmp = obj['date_play'].split(/[- ]/,3);
    return tmp[1] + '-' + tmp[2] + '-' + tmp[0];
});
console.log(newDates);