Javascript Date now()

Introduction

The Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.

Because now() is a static method of Date, use it as Date.now().

Date.now() returns the current timestamp.

It is equivalent to new Date().getTime().

It doesn't create a Date object.

The following code uses Date now() method to do benchmark.

let start = Date.now(); // milliseconds count from 1 Jan 1970

// do the job//ww w.j  a  v a2s.  c o  m
for (let i = 0; i < 100000; i++) {
  let doSomething = i * i * i;
}

let end = Date.now(); // done

console.log( `The loop took ${end - start} ms` ); // subtract numbers, not dates

The following code uses Date.now() to do benchmark.

There are two methods

  • the first uses a date-to-number transform
  • the second uses date.getTime() to get the date in ms.

Their result is always the same.

function diffSubtract(date1, date2) {
  return date2 - date1;
}

function diffGetTime(date1, date2) {
  return date2.getTime() - date1.getTime();
}

function bench(f) {
  let date1 = new Date(0);
  let date2 = new Date();

  let start = Date.now();
  for (let i = 0; i < 100000; i++)
       f(date1, date2);//w  w  w.j av a  2s  .  c o  m
  return Date.now() - start;
}

let time1 = 0;
let time2 = 0;

// run bench(upperSlice) and bench(upperLoop) each 10 times alternating
for (let i = 0; i < 10; i++) {
  time1 += bench(diffSubtract);
  time2 += bench(diffGetTime);
}

console.log( 'Total time for diffSubtract: ' + time1 );
console.log( 'Total time for diffGetTime: ' + time2 );

Calculate the number of years since 1970/01/01:

var minutes = 1000 * 60;
var hours = minutes * 60;
var days = hours * 24;
var years = days * 365;
var t = Date.now();

var y = Math.round(t / years);

console.log(y);/*from  w w w  .  j  av  a 2s  .  com*/



PreviousNext

Related