How can I get a timestamp in JavaScript?
Something similar to Unix timestamp, that is, a single number that represents the current time and date. Either as a number or a string.
This question is related to
javascript
date
datetime
timestamp
unix-timestamp
As of writing this, the top answer is 9 years old, and a lot has changed since then - not least, we have near universal support for a non-hacky solution:
Date.now()
If you want to be absolutely certain that this won't break in some ancient (pre ie9) browser, you can put it behind a check, like so:
const currentTimestamp = (!Date.now ? +new Date() : Date.now());
This will return the milliseconds since epoch time, of course, not seconds.
This one has a solution : which converts unixtime stamp to tim in js try this
var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();
Get TimeStamp In JavaScript
In JavaScript, a timestamp is the number of milliseconds that have passed since January 1, 1970.
If you don't intend to support < IE8, you can use
new Date().getTime(); + new Date(); and Date.now();
to directly get the timestamp without having to create a new Date object.
To return the required timestamp
new Date("11/01/2018").getTime()
console.log(new Date().valueOf()); // returns the number of milliseconds since the epoch
_x000D_
This seems to work.
console.log(clock.now);
// returns 1444356078076
console.log(clock.format(clock.now));
//returns 10/8/2015 21:02:16
console.log(clock.format(clock.now + clock.add(10, 'minutes')));
//returns 10/8/2015 21:08:18
var clock = {
now:Date.now(),
add:function (qty, units) {
switch(units.toLowerCase()) {
case 'weeks' : val = qty * 1000 * 60 * 60 * 24 * 7; break;
case 'days' : val = qty * 1000 * 60 * 60 * 24; break;
case 'hours' : val = qty * 1000 * 60 * 60; break;
case 'minutes' : val = qty * 1000 * 60; break;
case 'seconds' : val = qty * 1000; break;
default : val = undefined; break;
}
return val;
},
format:function (timestamp){
var date = new Date(timestamp);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
// Will display time in xx/xx/xxxx 00:00:00 format
return formattedTime = month + '/' +
day + '/' +
year + ' ' +
hours + ':' +
minutes.substr(-2) +
':' + seconds.substr(-2);
}
};
var time = Date.now || function() {
return +new Date;
};
time();
var d = new Date();
console.log(d.valueOf());
var time = Date.now || function() {
return +new Date;
};
time();
In addition to the other options, if you want a dateformat ISO, you get can get it directly
console.log(new Date().toISOString());
_x000D_
Here is another solution to generate a timestamp in JavaScript - including a padding method for single numbers - using day, month, year, hour, minute and seconds in its result (working example at jsfiddle):
var pad = function(int) { return int < 10 ? 0 + int : int; };
var timestamp = new Date();
timestamp.day = [
pad(timestamp.getDate()),
pad(timestamp.getMonth() + 1), // getMonth() returns 0 to 11.
timestamp.getFullYear()
];
timestamp.time = [
pad(timestamp.getHours()),
pad(timestamp.getMinutes()),
pad(timestamp.getSeconds())
];
timestamp.now = parseInt(timestamp.day.join("") + timestamp.time.join(""));
alert(timestamp.now);
Moment.js can abstract away a lot of the pain in dealing with Javascript Dates.
See: http://momentjs.com/docs/#/displaying/unix-timestamp/
moment().unix();
For a timestamp with microsecond resolution, there's performance.now
:
function time() {
return performance.now() + performance.timing.navigationStart;
}
This could for example yield 1436140826653.139
, while Date.now
only gives 1436140826653
.
jQuery provides its own method to get the timestamp:
var timestamp = $.now();
(besides it just implements (new Date).getTime()
expression)
sometime I need it in objects for xmlhttp calls, so I do like this.
timestamp : parseInt(new Date().getTime()/1000, 10)
var timestamp = Number(new Date()); // current time as number
You can only use
var timestamp = new Date().getTime();_x000D_
console.log(timestamp);
_x000D_
to get the current timestamp. No need to do anything extra.
I learned a really cool way of converting a given Date object to a Unix timestamp from the source code of JQuery Cookie the other day.
Here's an example:
var date = new Date();
var timestamp = +date;
I provide multiple solutions with descriptions in this answer. Feel free to ask questions if anything is unclear
PS: sadly someone merged this to the top answer without giving credit.
Quick and dirty solution:
Date.now() /1000 |0
Warning: it might break in 2038 and return negative numbers if you do the
|0
magic. UseMath.floor()
instead by that time
Math.floor()
solution:
Math.floor(Date.now() /1000);
Some nerdy alternative by Derek ???? taken from the comments below this answer:
new Date/1e3|0
Polyfill to get Date.now()
working:
To get it working in IE you could do this (Polyfill from MDN):
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
If you do not care about the year / day of week / daylight saving time you could strip it away and use this after 2038:
var now = (function () {
var year = new Date(new Date().getFullYear().toString()).getTime();
return function () {
return Date.now() - year
}
})();
Some output of how it will look:
new Date() Thu Oct 29 2015 08:46:30 GMT+0100 (Mitteleuropäische Zeit ) new Date(now()) Thu Oct 29 1970 09:46:30 GMT+0100 (Mitteleuropäische Zeit )
Of course it will break daylight saving time but depending on what you are building this might be useful to you if you need to do binary operations on timestamps after int32 will break in 2038.
This will also return negative values but only if the user of that PC you are running your code on is changing their PC's clock at least to 31th of december of the previous year.
If you just want to know the relative time from the point of when the code was run through first you could use something like this:
var relativeTime = (function () {
var start = Date.now();
return function () {
return Date.now() - start
}
})();
In case you are using jQuery you could use $.now()
as described in jQuery's Docs which makes the polyfill obsolete since $.now()
internally does the same thing: (new Date).getTime()
If you are just happy about jQuery's version consider upvoting this answer since I did not find it myself.
Now a tiny explaination of what |0
does:
By providing |
, you tell the interpreter to do a binary OR operation. Bit operations require absolute numbers which turns the decimal result from Date.now() / 1000
into an integer.
During that conversion, decimals are removed, resulting in the same result as using Math.floor()
but using less code.
Be warned though: it will convert a 64 bit double to a 32 bit integer. This will result in information loss when dealing with huge numbers. Timestamps will break after 2038 due to 32 bit integer overflow.
For further information about Date.now
follow this link: Date.now()
@ MDN
If it is for logging purposes, you can use ISOString
new Date().toISOString()
"2019-05-18T20:02:36.694Z"
The code Math.floor(new Date().getTime() / 1000)
can be shortened to new Date / 1E3 | 0
.
Consider to skip direct getTime()
invocation and use | 0
as a replacement for Math.floor()
function.
It's also good to remember 1E3
is a shorter equivalent for 1000
(uppercase E is preferred than lowercase to indicate 1E3
as a constant).
As a result you get the following:
var ts = new Date / 1E3 | 0;_x000D_
_x000D_
console.log(ts);
_x000D_
there are many ways to do it.
Date.now()
new Date().getTime()
new Date().valueOf()
To get the timestamp in seconds, convert it using:
Math.floor(Date.now() / 1000)
Today - 2020.04.23 I perform tests for chosen solutions. I tested on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0
Date.now()
(E) is fastest on Chrome and Safari and second fast on Firefox and this is probably best choice for fast cross-browser solutionperformance.now()
(G), what is surprising, is more than 100x faster than other solutions on Firefox but slowest on ChromeResults for chrome
You can perform test on your machine HERE
Code used in tests is presented in below snippet
function A() {
return new Date().getTime();
}
function B() {
return new Date().valueOf();
}
function C() {
return +new Date();
}
function D() {
return new Date()*1;
}
function E() {
return Date.now();
}
function F() {
return Number(new Date());
}
function G() {
// this solution returns time counted from loading the page.
// (and on Chrome it gives better precission)
return performance.now();
}
// TEST
log = (n,f) => console.log(`${n} : ${f()}`);
log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('F',F);
log('G',G);
_x000D_
This snippet only presents code used in external benchmark
_x000D_
I learned a really cool way of converting a given Date object to a Unix timestamp from the source code of JQuery Cookie the other day.
Here's an example:
var date = new Date();
var timestamp = +date;
var time = Date.now || function() {
return +new Date;
};
time();
For a timestamp with microsecond resolution, there's performance.now
:
function time() {
return performance.now() + performance.timing.navigationStart;
}
This could for example yield 1436140826653.139
, while Date.now
only gives 1436140826653
.
sometime I need it in objects for xmlhttp calls, so I do like this.
timestamp : parseInt(new Date().getTime()/1000, 10)
Just to add up, here's a function to return a timestamp string in Javascript. Example: 15:06:38 PM
function displayTime() {
var str = "";
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
if (minutes < 10) {
minutes = "0" + minutes
}
if (seconds < 10) {
seconds = "0" + seconds
}
str += hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
str += "PM"
} else {
str += "AM"
}
return str;
}
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
Get TimeStamp In JavaScript
In JavaScript, a timestamp is the number of milliseconds that have passed since January 1, 1970.
If you don't intend to support < IE8, you can use
new Date().getTime(); + new Date(); and Date.now();
to directly get the timestamp without having to create a new Date object.
To return the required timestamp
new Date("11/01/2018").getTime()
// The Current Unix Timestamp_x000D_
// 1443534720 seconds since Jan 01 1970. (UTC)_x000D_
_x000D_
// seconds_x000D_
console.log(Math.floor(new Date().valueOf() / 1000)); // 1443534720_x000D_
console.log(Math.floor(Date.now() / 1000)); // 1443534720_x000D_
console.log(Math.floor(new Date().getTime() / 1000)); // 1443534720_x000D_
_x000D_
// milliseconds_x000D_
console.log(Math.floor(new Date().valueOf())); // 1443534720087_x000D_
console.log(Math.floor(Date.now())); // 1443534720087_x000D_
console.log(Math.floor(new Date().getTime())); // 1443534720087_x000D_
_x000D_
// jQuery_x000D_
// seconds_x000D_
console.log(Math.floor($.now() / 1000)); // 1443534720_x000D_
// milliseconds_x000D_
console.log($.now()); // 1443534720087
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
var d = new Date();
console.log(d.valueOf());
One I haven't seen yet
Math.floor(Date.now() / 1000); // current time in seconds
Another one I haven't seen yet is
var _ = require('lodash'); // from here https://lodash.com/docs#now
_.now();
time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);
var timestamp = Number(new Date()); // current time as number
I like this, because it is small:
+new Date
I also like this, because it is just as short and is compatible with modern browsers, and over 500 people voted that it is better:
Date.now()
Date, a native object in JavaScript is the way we get all data about time.
Just be careful in JavaScript the timestamp depends on the client computer set, so it's not 100% accurate timestamp. To get the best result, you need to get the timestamp from the server-side.
Anyway, my preferred way is using vanilla. This is a common way of doing it in JavaScript:
Date.now(); //return 1495255666921
In MDN it's mentioned as below:
The Date.now() method returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
Because now() is a static method of Date, you always use it as Date.now().
If you using a version below ES5, Date.now();
not works and you need to use:
new Date().getTime();
I highly recommend using moment.js
. To get the number of milliseconds since UNIX epoch, do
moment().valueOf()
To get the number of seconds since UNIX epoch, do
moment().unix()
You can also convert times like so:
moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()
I do that all the time. No pun intended.
To use moment.js
in the browser:
<script src="moment.js"></script>
<script>
moment().valueOf();
</script>
For more details, including other ways of installing and using MomentJS, see their docs
I like this, because it is small:
+new Date
I also like this, because it is just as short and is compatible with modern browsers, and over 500 people voted that it is better:
Date.now()
Here is another solution to generate a timestamp in JavaScript - including a padding method for single numbers - using day, month, year, hour, minute and seconds in its result (working example at jsfiddle):
var pad = function(int) { return int < 10 ? 0 + int : int; };
var timestamp = new Date();
timestamp.day = [
pad(timestamp.getDate()),
pad(timestamp.getMonth() + 1), // getMonth() returns 0 to 11.
timestamp.getFullYear()
];
timestamp.time = [
pad(timestamp.getHours()),
pad(timestamp.getMinutes()),
pad(timestamp.getSeconds())
];
timestamp.now = parseInt(timestamp.day.join("") + timestamp.time.join(""));
alert(timestamp.now);
more simpler way:
var timeStamp=event.timestamp || new Date().getTime();
One I haven't seen yet
Math.floor(Date.now() / 1000); // current time in seconds
Another one I haven't seen yet is
var _ = require('lodash'); // from here https://lodash.com/docs#now
_.now();
Here is a simple function to generate timestamp in the format: mm/dd/yy hh:mi:ss
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
For lodash and underscore users, use _.now
.
var timestamp = _.now(); // in milliseconds
In addition to the other options, if you want a dateformat ISO, you get can get it directly
console.log(new Date().toISOString());
_x000D_
The Date.getTime()
method can be used with a little tweak:
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.
Divide the result by 1000 to get the Unix timestamp, floor
if necessary:
(new Date).getTime() / 1000
The Date.valueOf()
method is functionally equivalent to Date.getTime()
, which makes it possible to use arithmetic operators on date object to achieve identical results. In my opinion, this approach affects readability.
This one has a solution : which converts unixtime stamp to tim in js try this
var a = new Date(UNIX_timestamp*1000);
var hour = a.getUTCHours();
var min = a.getUTCMinutes();
var sec = a.getUTCSeconds();
If want a basic way to generate a timestamp in Node.js this works well.
var time = process.hrtime();
var timestamp = Math.round( time[ 0 ] * 1e3 + time[ 1 ] / 1e6 );
Our team is using this to bust cache in a localhost environment. The output is /dist/css/global.css?v=245521377
where 245521377
is the timestamp generated by hrtime()
.
Hopefully this helps, the methods above can work as well but I found this to be the simplest approach for our needs in Node.js.
console.log(new Date().valueOf()); // returns the number of milliseconds since the epoch
_x000D_
If want a basic way to generate a timestamp in Node.js this works well.
var time = process.hrtime();
var timestamp = Math.round( time[ 0 ] * 1e3 + time[ 1 ] / 1e6 );
Our team is using this to bust cache in a localhost environment. The output is /dist/css/global.css?v=245521377
where 245521377
is the timestamp generated by hrtime()
.
Hopefully this helps, the methods above can work as well but I found this to be the simplest approach for our needs in Node.js.
var my_timestamp = ~~(Date.now()/1000);
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
For lodash and underscore users, use _.now
.
var timestamp = _.now(); // in milliseconds
Here is a simple function to generate timestamp in the format: mm/dd/yy hh:mi:ss
function getTimeStamp() {
var now = new Date();
return ((now.getMonth() + 1) + '/' +
(now.getDate()) + '/' +
now.getFullYear() + " " +
now.getHours() + ':' +
((now.getMinutes() < 10)
? ("0" + now.getMinutes())
: (now.getMinutes())) + ':' +
((now.getSeconds() < 10)
? ("0" + now.getSeconds())
: (now.getSeconds())));
}
JavaScript works with the number of milliseconds since the epoch whereas most other languages work with the seconds. You could work with milliseconds but as soon as you pass a value to say PHP, the PHP native functions will probably fail. So to be sure I always use the seconds, not milliseconds.
This will give you a Unix timestamp (in seconds):
var unix = Math.round(+new Date()/1000);
This will give you the milliseconds since the epoch (not Unix timestamp):
var milliseconds = new Date().getTime();
The Date.getTime()
method can be used with a little tweak:
The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.
Divide the result by 1000 to get the Unix timestamp, floor
if necessary:
(new Date).getTime() / 1000
The Date.valueOf()
method is functionally equivalent to Date.getTime()
, which makes it possible to use arithmetic operators on date object to achieve identical results. In my opinion, this approach affects readability.
I highly recommend using moment.js
. To get the number of milliseconds since UNIX epoch, do
moment().valueOf()
To get the number of seconds since UNIX epoch, do
moment().unix()
You can also convert times like so:
moment('2015-07-12 14:59:23', 'YYYY-MM-DD HH:mm:ss').valueOf()
I do that all the time. No pun intended.
To use moment.js
in the browser:
<script src="moment.js"></script>
<script>
moment().valueOf();
</script>
For more details, including other ways of installing and using MomentJS, see their docs
The advised, proper way is Number(new Date())
,
in terms of code- readability,
Also, UglifyJS and Google-Closure-Compiler will lower the complexity of the parsed code-logic-tree (relevant if you are using one of them to obscure/minify your code).
for Unix timestamp, which has a lower time resolution, just divide current number with 1000
, keeping the whole.
Today - 2020.04.23 I perform tests for chosen solutions. I tested on MacOs High Sierra 10.13.6 on Chrome 81.0, Safari 13.1, Firefox 75.0
Date.now()
(E) is fastest on Chrome and Safari and second fast on Firefox and this is probably best choice for fast cross-browser solutionperformance.now()
(G), what is surprising, is more than 100x faster than other solutions on Firefox but slowest on ChromeResults for chrome
You can perform test on your machine HERE
Code used in tests is presented in below snippet
function A() {
return new Date().getTime();
}
function B() {
return new Date().valueOf();
}
function C() {
return +new Date();
}
function D() {
return new Date()*1;
}
function E() {
return Date.now();
}
function F() {
return Number(new Date());
}
function G() {
// this solution returns time counted from loading the page.
// (and on Chrome it gives better precission)
return performance.now();
}
// TEST
log = (n,f) => console.log(`${n} : ${f()}`);
log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('F',F);
log('G',G);
_x000D_
This snippet only presents code used in external benchmark
_x000D_
more simpler way:
var timeStamp=event.timestamp || new Date().getTime();
The code Math.floor(new Date().getTime() / 1000)
can be shortened to new Date / 1E3 | 0
.
Consider to skip direct getTime()
invocation and use | 0
as a replacement for Math.floor()
function.
It's also good to remember 1E3
is a shorter equivalent for 1000
(uppercase E is preferred than lowercase to indicate 1E3
as a constant).
As a result you get the following:
var ts = new Date / 1E3 | 0;_x000D_
_x000D_
console.log(ts);
_x000D_
Moment.js can abstract away a lot of the pain in dealing with Javascript Dates.
See: http://momentjs.com/docs/#/displaying/unix-timestamp/
moment().unix();
To get time, month, day, year separately this will work
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var timestamp = Number(new Date()); // current time as number
time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);
I provide multiple solutions with descriptions in this answer. Feel free to ask questions if anything is unclear
PS: sadly someone merged this to the top answer without giving credit.
Quick and dirty solution:
Date.now() /1000 |0
Warning: it might break in 2038 and return negative numbers if you do the
|0
magic. UseMath.floor()
instead by that time
Math.floor()
solution:
Math.floor(Date.now() /1000);
Some nerdy alternative by Derek ???? taken from the comments below this answer:
new Date/1e3|0
Polyfill to get Date.now()
working:
To get it working in IE you could do this (Polyfill from MDN):
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
If you do not care about the year / day of week / daylight saving time you could strip it away and use this after 2038:
var now = (function () {
var year = new Date(new Date().getFullYear().toString()).getTime();
return function () {
return Date.now() - year
}
})();
Some output of how it will look:
new Date() Thu Oct 29 2015 08:46:30 GMT+0100 (Mitteleuropäische Zeit ) new Date(now()) Thu Oct 29 1970 09:46:30 GMT+0100 (Mitteleuropäische Zeit )
Of course it will break daylight saving time but depending on what you are building this might be useful to you if you need to do binary operations on timestamps after int32 will break in 2038.
This will also return negative values but only if the user of that PC you are running your code on is changing their PC's clock at least to 31th of december of the previous year.
If you just want to know the relative time from the point of when the code was run through first you could use something like this:
var relativeTime = (function () {
var start = Date.now();
return function () {
return Date.now() - start
}
})();
In case you are using jQuery you could use $.now()
as described in jQuery's Docs which makes the polyfill obsolete since $.now()
internally does the same thing: (new Date).getTime()
If you are just happy about jQuery's version consider upvoting this answer since I did not find it myself.
Now a tiny explaination of what |0
does:
By providing |
, you tell the interpreter to do a binary OR operation. Bit operations require absolute numbers which turns the decimal result from Date.now() / 1000
into an integer.
During that conversion, decimals are removed, resulting in the same result as using Math.floor()
but using less code.
Be warned though: it will convert a 64 bit double to a 32 bit integer. This will result in information loss when dealing with huge numbers. Timestamps will break after 2038 due to 32 bit integer overflow.
For further information about Date.now
follow this link: Date.now()
@ MDN
To get time, month, day, year separately this will work
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
Any browsers not supported Date.now, you can use this for get current date time:
currentTime = Date.now() || +new Date()
If it is for logging purposes, you can use ISOString
new Date().toISOString()
"2019-05-18T20:02:36.694Z"
JavaScript works with the number of milliseconds since the epoch whereas most other languages work with the seconds. You could work with milliseconds but as soon as you pass a value to say PHP, the PHP native functions will probably fail. So to be sure I always use the seconds, not milliseconds.
This will give you a Unix timestamp (in seconds):
var unix = Math.round(+new Date()/1000);
This will give you the milliseconds since the epoch (not Unix timestamp):
var milliseconds = new Date().getTime();
You can only use
var timestamp = new Date().getTime();_x000D_
console.log(timestamp);
_x000D_
to get the current timestamp. No need to do anything extra.
The advised, proper way is Number(new Date())
,
in terms of code- readability,
Also, UglifyJS and Google-Closure-Compiler will lower the complexity of the parsed code-logic-tree (relevant if you are using one of them to obscure/minify your code).
for Unix timestamp, which has a lower time resolution, just divide current number with 1000
, keeping the whole.
Date, a native object in JavaScript is the way we get all data about time.
Just be careful in JavaScript the timestamp depends on the client computer set, so it's not 100% accurate timestamp. To get the best result, you need to get the timestamp from the server-side.
Anyway, my preferred way is using vanilla. This is a common way of doing it in JavaScript:
Date.now(); //return 1495255666921
In MDN it's mentioned as below:
The Date.now() method returns the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
Because now() is a static method of Date, you always use it as Date.now().
If you using a version below ES5, Date.now();
not works and you need to use:
new Date().getTime();
Just to add up, here's a function to return a timestamp string in Javascript. Example: 15:06:38 PM
function displayTime() {
var str = "";
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
if (minutes < 10) {
minutes = "0" + minutes
}
if (seconds < 10) {
seconds = "0" + seconds
}
str += hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
str += "PM"
} else {
str += "AM"
}
return str;
}
This seems to work.
console.log(clock.now);
// returns 1444356078076
console.log(clock.format(clock.now));
//returns 10/8/2015 21:02:16
console.log(clock.format(clock.now + clock.add(10, 'minutes')));
//returns 10/8/2015 21:08:18
var clock = {
now:Date.now(),
add:function (qty, units) {
switch(units.toLowerCase()) {
case 'weeks' : val = qty * 1000 * 60 * 60 * 24 * 7; break;
case 'days' : val = qty * 1000 * 60 * 60 * 24; break;
case 'hours' : val = qty * 1000 * 60 * 60; break;
case 'minutes' : val = qty * 1000 * 60; break;
case 'seconds' : val = qty * 1000; break;
default : val = undefined; break;
}
return val;
},
format:function (timestamp){
var date = new Date(timestamp);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
// Will display time in xx/xx/xxxx 00:00:00 format
return formattedTime = month + '/' +
day + '/' +
year + ' ' +
hours + ':' +
minutes.substr(-2) +
':' + seconds.substr(-2);
}
};
As of writing this, the top answer is 9 years old, and a lot has changed since then - not least, we have near universal support for a non-hacky solution:
Date.now()
If you want to be absolutely certain that this won't break in some ancient (pre ie9) browser, you can put it behind a check, like so:
const currentTimestamp = (!Date.now ? +new Date() : Date.now());
This will return the milliseconds since epoch time, of course, not seconds.
Any browsers not supported Date.now, you can use this for get current date time:
currentTime = Date.now() || +new Date()
// The Current Unix Timestamp_x000D_
// 1443534720 seconds since Jan 01 1970. (UTC)_x000D_
_x000D_
// seconds_x000D_
console.log(Math.floor(new Date().valueOf() / 1000)); // 1443534720_x000D_
console.log(Math.floor(Date.now() / 1000)); // 1443534720_x000D_
console.log(Math.floor(new Date().getTime() / 1000)); // 1443534720_x000D_
_x000D_
// milliseconds_x000D_
console.log(Math.floor(new Date().valueOf())); // 1443534720087_x000D_
console.log(Math.floor(Date.now())); // 1443534720087_x000D_
console.log(Math.floor(new Date().getTime())); // 1443534720087_x000D_
_x000D_
// jQuery_x000D_
// seconds_x000D_
console.log(Math.floor($.now() / 1000)); // 1443534720_x000D_
// milliseconds_x000D_
console.log($.now()); // 1443534720087
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
there are many ways to do it.
Date.now()
new Date().getTime()
new Date().valueOf()
To get the timestamp in seconds, convert it using:
Math.floor(Date.now() / 1000)
var time = Date.now || function() {
return +new Date;
};
time();
jQuery provides its own method to get the timestamp:
var timestamp = $.now();
(besides it just implements (new Date).getTime()
expression)
var my_timestamp = ~~(Date.now()/1000);
Source: Stackoverflow.com