Stef Kors
Stef Kors

Reputation: 310

Changing date format javascript

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;
}

Upvotes: 3

Views: 108

Answers (4)

iplus26
iplus26

Reputation: 2647

Try moment.js

var timestamp = 1427457730;
var date      = '2015-04-10T09:12:22Z';

var m1 = moment(timestamp);
var m2 = moment(date);

console.log(m1);
console.log(m2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>

You can use .format() method in moment to parse the date to whatever format you want, just like:

m2.format('YYYY MMM DD ddd HH:mm:ss') // 2015 Apr 10 Fri 17:12:22

Check out the docs for more format tokens.

Upvotes: 3

adeneo
adeneo

Reputation: 318332

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

Upvotes: 2

kctang
kctang

Reputation: 11202

Take a look at http://momentjs.com/. It is THE date/time formatting library for JavaScript - very simple to use, extremely flexible.

Upvotes: 2

robertklep
robertklep

Reputation: 203514

Here's one option:

var timestamp  = 1427457730;
var date       = new Date(timestamp * 1000); // wants milliseconds, not seconds
var dateString = date.toISOString().replace(/\.\d+Z/, 'Z'); // remove the ms

dateString will now be 2015-03-27T12:02:10Z.

Upvotes: 4

Related Questions