convert iso date to milliseconds in javascript

后端 未结 10 1924
不知归路
不知归路 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.

    0 讨论(0)
  • 2020-11-29 01:45

    Yes, you can do this in a single line

    let ms = Date.parse('2019-05-15 07:11:10.673Z');
    console.log(ms);//1557904270673
    
    0 讨论(0)
  • Another solution could be to use Number object parser like this:

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

    This converts to milliseconds just like getTime() on Date object

    0 讨论(0)
  • 2020-11-29 01:46

    var date = new Date(date_string); var milliseconds = date.getTime();

    This worked for me!

    0 讨论(0)
提交回复
热议问题