Changing the format of the javascript date

advertisements

I'm pulling some data from two different APIs and I want to the objects later on.

However, I'm getting two different date formats: this format "1427457730" and this format "2015-04-10T09:12:22Z". How can I change the format of one of these so I have the same format to work with?

$.each(object, function(index) {
  date = object[index].updated_at;
}


What you probably want in javascript, are date objects.
The first string is seconds since epoch, javascript needs milliseconds, so multiply it by 1000;
The second string is a valid ISO date, so if the string contains a hyphen just pass it into new Date.

var date = returned_date.indexOf('-') !== -1 ? returned_date : returned_date * 1000;

var date_object = new Date(date);

Making both types into date objects, you could even turn that into a handy function

function format_date(date) {
    return new Date(date.indexOf('-') !== -1 ? date : date * 1000);
}

FIDDLE