javascript tutorial - timestamp in javaScript - javascript - java script - javascript array



Problem:

How to get a timestamp in JavaScript?

Solution 1:

var timeStampInMs = window.performance && window.performance.now && window.performance.timing && window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now();

console.log(timeStampInMs, Date.now());
click below button to copy the code. By JavaScript tutorial team

Short & Snazzy:

+ new Date()
if (!Date.now) {
    Date.now = function() { return new Date().getTime(); }
}
click below button to copy the code. By JavaScript tutorial team

To get the timestamp in seconds, we can use:

Math.floor(Date.now() / 1000)
click below button to copy the code. By JavaScript tutorial team

Or alternatively we could use:

Date.now() / 1000 | 0
new Date().getTime()
Math.round(new Date().getTime()/1000)
new Date().valueOf()
click below button to copy the code. By JavaScript tutorial team

Solution 2:

We like this, because it is small:

+new Date
click below button to copy the code. By JavaScript tutorial team

We also like this, because it is just as short and is compatible with modern browsers, and over 357 people voted that it's better:

Date.now()
click below button to copy the code. By JavaScript tutorial team

Solution 3:

var unix = Math.round(+new Date()/1000);
click below button to copy the code. By JavaScript tutorial team

This will give we the milliseconds since the epoch (not Unix timestamp):

var milliseconds = new Date().getTime();
click below button to copy the code. By JavaScript tutorial team

Solution 4:

var time = Date.now || function() {
  return +new Date;
};

time();
click below button to copy the code. By JavaScript tutorial team

Solution 5:

var timestamp = Number(new Date()); // current time as number
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - timestamp in javaScript