Fizzix
Fizzix

Reputation: 24395

How to convert milliseconds to a readable date with Javascript?

I have a milliseconds integer, and I am trying to convert it to a readable date in the format of yyyy MM dd (2014-08-06).

var maxDate = 1407267771429;
maxDate = new Date(maxDate);
maxDateFinal = maxDate.toString('yyyy MM dd');

WORKING EXAMPLE

Although, maxDateFinal always seems to equal Wed Aug 06 2014 05:42:51 GMT+1000 (E. Australia Standard Time)

I have added console.log() after each call in my fiddle to demonstrate the change of the variables, although it seems as if toString() is doing absolutely nothing to the date at all.

Upvotes: 3

Views: 8122

Answers (2)

zeroviscosity
zeroviscosity

Reputation: 126

Unfortunately JavaScript's Date does not provide arbitrary formatting with the toString() method (or any other method). To get your date in yyyy-mm-dd format, you could use the toISOString() and then the substr(start, length) method. For instance:

var maxDate = new Date(1407267771429);
var isoDate = maxDate.toISOString(); // 2014-08-05T19:42:51.429Z
isoDate.substr(0, 10); // 2014-08-05

This should work in all major browsers including IE9+. To support support IE8 and older browsers, you could do something like this:

function toISODate(milliseconds) {
    var date = new Date(milliseconds);
    var y = date.getFullYear()
    var m = date.getMonth() + 1;
    var d = date.getDate();
    m = (m < 10) ? '0' + m : m;
    d = (d < 10) ? '0' + d : d;
    return [y, m, d].join('-');
}

Alternatively you could look into something like Moment.js (http://momentjs.com/) or jquery-dateFormat (https://github.com/phstc/jquery-dateFormat).

Upvotes: 3

Ry-
Ry-

Reputation: 225273

JavaScript doesn’t have built-in date formatting. You can do it yourself, but there are also a few libraries out there.

function pad(s, width, character) {
    return new Array(width - s.toString().length + 1).join(character) + s;
}

var maxDate = new Date(1407267771429);
var maxDateFormatted =
    maxDate.getFullYear() +
    ' ' + pad(maxDate.getMonth() + 1, 2, '0') +
    ' ' + pad(maxDate.getDate(), 2, '0');

Upvotes: 3

Related Questions