简体   繁体   中英

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

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 .

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 .

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM