How can I convert a date into an integer?

JavascriptDate

Javascript Problem Overview


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"
];

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

Using the builtin Date.parse function which accepts input in ISO8601 format and directly returns the desired integer return value:

var dates_as_int = dates.map(Date.parse);

Solution 3 - Javascript

Here what you can try:

var d = Date.parse("2016-07-19T20:23:01.804Z");
alert(d); //this is in milliseconds

Solution 4 - Javascript

You can run it through Number()

var myInt = Number(new Date(dates_as_int[0]));

> If the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC.

Use of Number()

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPablo.KView Question on Stackoverflow
Solution 1 - JavascriptAlex BassView Answer on Stackoverflow
Solution 2 - JavascriptAlnitakView Answer on Stackoverflow
Solution 3 - JavascriptbradView Answer on Stackoverflow
Solution 4 - JavascriptGary HolidayView Answer on Stackoverflow