3

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.

Fizzix
  • 23,679
  • 38
  • 110
  • 176
  • what is the source of your `var maxDate`? Minitech's answer seems correct. – sidewaiise Sep 24 '14 at 01:29
  • toString simply just prints out the date, It does not format it. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString – andrex Sep 24 '14 at 01:30
  • possible duplicate of [how to format javascript date](http://stackoverflow.com/questions/3552461/how-to-format-javascript-date) – andrex Sep 24 '14 at 01:34

2 Answers2

3

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');
Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Ahh alright, interesting. Does jQuery have built in date formatting? The solution you posted works very well, cheers. – Fizzix Sep 24 '14 at 01:31
3

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).