convert iso date to milliseconds in javascript

后端 未结 10 1951
不知归路
不知归路 2020-11-29 00:40

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

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-29 01:44

    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.

提交回复
热议问题