Javascript Date with arithmetic operators

Introduction

We can use Date value in arithmetic calculation. The date value is converted to number.

When a Date object is converted to number, it becomes the timestamp same as date.getTime():

let date = new Date();
console.log(+date); // the number of milliseconds, same as date.getTime()

When date values are subtracted, the result is their difference in ms.

That can be used for time measurements:

let start = new Date(); // start measuring time

// do the job/*from ww w  .  jav  a 2  s . co  m*/
for (let i = 0; i < 100000; i++) {
  let doSomething = i * i * i;
}

let end = new Date(); // end measuring time

console.log( `The loop took ${end - start} ms` );



PreviousNext

Related