whisps11
whisps11

Reputation: 75

JSON date to normal JS date

I have a similar problem as asked by user7397787 in convert json date to javascript date format.

What I have is a JSON string with MySQL table data. One of the data is date. I converted this date to normal date using my own code as shown below:

 var comp_date = [];
 for (var i in data) {
   var fields =  data[i].myDate.split('/');
   var mm = fields[0];
   var dd = fields[1];
   var yy = fields[2];
   mm < 10 ? '0' + mm :  mm; 
   dd < 10 ? '0' + dd : dd;
   var formatted_date = mm + "/" + dd + "/" + yy;                
   var dt = new Date(formatted_date);
   comp_date.push(dt);
 }

This date is used in a bar graph. Now what happens is that the date along x-axis is displayed like this Sat Sep 09 2017 00:00:00 GMT+0500 (Time Zone here) and on y-axis the date is displayed like this 1505900000000, 1505800000000, 1505700000000, 1505600000000. I want date on both side in mm-dd-yyyy format.

I tried to convert date with the method explained by sammysaglam in convert json date to javascript date format like this:

var date =  unix_to_readable( data[i].myDate);

But then I got all dates returned with the same value, which is 01-01-1970.

Anyone knows what's happening or what I'm doing wrong?

Thank you.

Upvotes: 1

Views: 733

Answers (1)

Doug E Fresh
Doug E Fresh

Reputation: 840

I took one of the numbers you said you were having trouble with 1505900000000. This code snippet shows how to get it into a readable string (by way of a date object) in javascript. If you run the snippet an alert will show you the date string you are looking for.

var dateNumberString = '1505900000000'; // This is what you get from JSON
var dateNumber = parseInt(dateNumberString); // make it a number
var date = new Date(dateNumber);// javascript will convert to date object for you
var dateString = date.toString(); // make it a string
alert(dateString);

Then to format the date the way you want it:

var dateObj = new Date();
var formattedString = getFormattedDate(dateObj);
alert(formattedString);

// This function takes a javscript date object
function getFormattedDate(date) {
  var year = date.getFullYear();
  var month = (date.getMonth() + 1).toString(); // javascript month is zero based 
  month = month.length > 1 ? month : '0' + month;
  var day = date.getDate().toString();
  day = day.length > 1 ? day : '0' + day;
  return month + '-' + day + '-' + year;
}

Upvotes: 1

Related Questions