Search code examples
javascriptdate

How can I convert a date into an integer?


I have an array of dates and have been using the map function to iterate through it, but I can't figure out the JavaScript code for converting them into integers.

This is the array of dates:

var dates_as_int = [
    "2016-07-19T20:23:01.804Z",
    "2016-07-20T15:43:54.776Z",
    "2016-07-22T14:53:38.634Z",
    "2016-07-25T14:39:34.527Z"
];

Solution

  • var dates = dates_as_int.map(function(dateStr) {
        return new Date(dateStr).getTime();
    });
    

    =>

    [1468959781804, 1469029434776, 1469199218634, 1469457574527]
    

    Update: ES6 version:

    const dates = dates_as_int.map(date => new Date(date).getTime())
    

    The getTime() method on the Date returns an “ECMAScript epoch”, which is the same as the UNIX epoch but in milliseconds. This is important to note as some other languages use UNIX timestamps which are in in seconds.

    The UNIX timestamp and is equivalent to the number of milliseconds since January 1st 1970. This is a date you might have seen before in databases or some apps, and it’s usually the sign of a bug.