Javascript Date getTime()

Introduction

Javascript Date getTime() returns the milliseconds representation of the date; same as valueOf().

The getTime() method returns the number of milliseconds since the Unix Epoch.

This method is functionally equivalent to the valueOf() method.

The following code uses getTime() for copying dates

Constructing a date object with the identical time value.

// Since month is zero based, birthday will be January 10, 1995
var birthday = new Date(1994, 12, 10);
var copy = new Date();
copy.setTime(birthday.getTime());/* w  w  w  .  jav a  2s  .  c  o m*/
console.log(birthday);
console.log(copy);

Measuring execution time

We can subtracting two subsequent getTime() calls on newly generated Date objects, give the time span between these two calls.

This can be used to calculate the executing time of some operations.

var end, start;//from   ww  w .  ja va  2 s . c om

start = new Date();
for (var i = 0; i < 1000; i++) {
  Math.sqrt(i);
}
end = new Date();

console.log('Operation took ' + (end.getTime() - start.getTime()) + ' msec');

We should use Date.now() to prevent instantiating unnecessary Date objects.

The following code uses Date.now() to do benchmark between getTime() and date-to-number transform.

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);//from  www . j a  v a  2s .  co  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 d = new Date();
var t= d.getTime();

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

console.log(y);/*w ww.ja va  2s  .c o  m*/



PreviousNext

Related