-4

I want to change date format from yyyy-MM-dd'T'HH:mm:ss.SSS'Z' to dd-mmm-yyyy when dates comes from JSON object. I am downloading this JSON using ng-csv plugin. Download functionality is working fine but I need to convert date format using JavaScript. I have JSON structure like this

[{
    "Dates": "2016-09-27T18:30:00.000Z",
    "ABC": 40,
    "PQR": 1,
    "XYZ": 18
}, {
    "Dates": "2016-10-02T18:30:00.000Z",
    "ABC": 43,
    "PQR": 11,
    "XYZ": 8
}, {
    "Dates": "2016-10-03T18:30:00.000Z",
    "ABC": 6,
    "PQR": 76,
    "XYZ": 34
}]

Any suggestion? Thanks in Advance.

Shubham
  • 1,755
  • 3
  • 17
  • 33
Pooja
  • 105
  • 4
  • 16

1 Answers1

-2

Try this

function getDate(dateVal) {

var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];

  var date1 = dateVal.split('T')[0];
  var date = new Date(date1);
  var getDay = date.getDate();
  var getMonth = date.getMonth() + 1;
  var getYear = date.getFullYear();
  alert(getDay +' '+ monthNames[getMonth]  + ' ' +getYear);
  return  getDay +'-'+ monthNames[getMonth] + '-' +getYear
}

getDate('2016-09-27T18:30:00.000Z');

var data = [
 {
"Dates": "2016-09-27T18:30:00.000Z",
"ABC": 40,
"PQR": 1,
"XYZ": 18
},{
"Dates": "2016-10-02T18:30:00.000Z",
"ABC": 43,
"PQR": 11,
"XYZ": 8
},{
"Dates": "2016-10-03T18:30:00.000Z",
"ABC": 6,
"PQR": 76,
"XYZ": 34
}
];
var temp = [];
for(var i=0; i<data.length;i++){

  temp[i] = getDate(data[i].Dates);
}

console.log(temp);

Working Fiddle

Arunkumar G
  • 126
  • 6
  • 1
    Code only answers are not that helpful. This not only converts the date, but shifts it to the local timezone so that it may represent a different date in different timezones. That should be explained in the answer. It also seems redundant to parse the string, create a Date, then read back the values that were just passed to the Date to generate a string. Why not just reformat the original string and avoid a Date entirely? That needs just 2 lines of code. – RobG Jul 13 '17 at 23:00