Search code examples
javascriptisoisodate

convert iso date to milliseconds in javascript


Can I convert iso date to milliseconds? for example I want to convert this iso

2012-02-10T13:19:11+0000

to milliseconds.

Because I want to compare current date from the created date. And created date is an iso date.


Solution

  • Try this

    var date = new Date("11/21/1987 16:00:00"); // some mock date
    var milliseconds = date.getTime(); 
    // This will return you the number of milliseconds
    // elapsed from January 1, 1970 
    // if your date is less than that date, the value will be negative
    
    console.log(milliseconds);

    EDIT

    You've provided an ISO date. It is also accepted by the constructor of the Date object

    var myDate = new Date("2012-02-10T13:19:11+0000");
    var result = myDate.getTime();
    console.log(result);

    Edit

    The best I've found is to get rid of the offset manually.

    var myDate = new Date("2012-02-10T13:19:11+0000");
    var offset = myDate.getTimezoneOffset() * 60 * 1000;
    
    var withOffset = myDate.getTime();
    var withoutOffset = withOffset - offset;
    console.log(withOffset);
    console.log(withoutOffset);

    Seems working. As far as problems with converting ISO string into the Date object you may refer to the links provided.

    EDIT

    Fixed the bug with incorrect conversion to milliseconds according to Prasad19sara's comment.