Integer addition/subtraction issues with the Date object

后端 未结 2 1993
北荒
北荒 2021-01-28 13:41

I was playing around with the native Date object, and I realised that subtraction works (returns an integer representing the total number of miliseconds between the two dates),

相关标签:
2条回答
  • 2021-01-28 14:01

    the + operator is overloaded for strings, - is not. You need to use

    var newVal=parseInt(new Date().getTime()) + 1000
    
    0 讨论(0)
  • 2021-01-28 14:13

    You can simply convert current date into milliseconds, add your desired increment then convert it back to date time format and there you have your incremented date:

    var d = new Date();
    alert("Current DateTime: " + d);
    var milliseconds = d.getTime();  //this will convert current date  into milliseconds.. 
    
    //Now youw want to progress the date by 3000ms.. simply add it to the current date time..
    milliseconds += 3000;
    
    d = new Date(milliseconds); //your new incremented date
    
    alert("After 3000ms: " + d);
    

    See the DEMO here

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