How do you get a timestamp in JavaScript?

Created 21.10.2008 09:29
Viewed 3.19M times
4274 votes

Something similar to Unix's timestamp, that is a single number that represents the current time and date. Either as a number or a string.

Answers 40

Short & Snazzy:

+ new Date()

A unary operator like plus triggers the valueOf method in the Date object and it returns the timestamp (without any alteration).


On almost all current browsers you can use to get the UTC timestamp in milliseconds; a notable exception to this is IE8 and earlier (see compatibility table).

You can easily make a shim for this, though:

if (! { = function() { return new Date().getTime(); }

To get the timestamp in seconds, you can use:

Math.floor( / 1000)

Or alternatively you could use: / 1000 | 0

Which should be slightly faster, but also less readable (also see this answer).

I would recommend using (with compatibility shim). It's slightly better because it's shorter & doesn't create a new Date object. However, if you don't want a shim & maximum compatibility, you could use the "old" method to get the timestamp in milliseconds:

new Date().getTime()

Which you can then convert to seconds like this:

Math.round(new Date().getTime()/1000)

And you can also use the valueOf method which we showed above:

new Date().valueOf()

Examples of each method

Timestamp in Milliseconds

var timeStampInMs = window.performance && && window.performance.timing && window.performance.timing.navigationStart ? + window.performance.timing.navigationStart :;


21.10.2008 09:32
In case you wonder about the logic of plus sign is: + is used as toInt() where it will neglect all the characters and return only numbers by Umair Riaz, 22.02.2021 10:26

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:
18.02.2011 00:33
This option is a bad idea. It's easily overlooked, looks like a typo, and is in reality relying on a language side-effect. I see bad code. by inanutshellus, 29.10.2012 15:51
@Billy As I recall it, I computed the timestamp in the two suggested solutions 1M times each, and calculated the average runtime. I ran it in Firefox and Chrome, with getTime being faster in both browsers. That said, even if it were (marginally) slower I'd choose new Date().getTime(). Luckily for me, the faster solution is already the legible solution! by inanutshellus, 08.07.2013 12:44
Agreed with @FabrícioMatté. Unary operator behavior may not be rudimentary, but if you haven't brushed up on it, don't expect to be able to function effectively in a lot of teams. by Jason T Featheringham, 18.07.2013 01:58
Not useful. This returned a time string (as in "Sat 14th...") when doing var foo = 'NEW-' + new Date; by Niklaus, 17.09.2013 10:38
@Niklaus That's because you're concatenating it to another string. In that case, new Date().toString() is called. by kirb, 02.10.2013 11:50
out of curiosity what is the +operator doing to make it come out like a string? by zadubz, 19.12.2014 10:47
+ is unary mathmatic in this case. typeof (+new Date()) evaluates to "number". Basically it's shorthand for new Date().valueOf() -- without the javascript function call. But don't write it this way, it looks like a typo. by ansiart, 20.12.2014 22:58
If it were covered by unit tests, it wouldn't be such a problem. by Rimian, 12.03.2015 10:40
@Niklaus in that case you would need another plus to act as the unary operator: 'NEW-' + +new Date by 1j01, 17.03.2015 19:42
The +new Date does not seem to work in Chrome 52, if the desired effect is to generate an integer. I am confident it worked on older Chromes. by Marcus Johansson, 04.09.2016 08:56
@MarcusJohansson people should be using if they are using a newer browser like Chrome. I tried this in Chrome 52 and Chrome Canary 55 and +new Date still worked. by xer0x, 08.09.2016 20:43
@FelixGagnon-Grenier I added because it is now the preferred way, and lots of people don't like +new Date. I like that daveb's answer now includes +new Date, and explains it, but it didn't used to either. by xer0x, 04.01.2017 00:15
So to retrieve a numeric value that is already inside your computer you create an object, call an operator that requires an int and triggers a conversion that calls a function (valueOf) that calls the class conversion method that calls the function (getTime) that finally retrieves the value that was already there. Then the object is abandoned to its destiny, and after 1000 iterations of the loop you have 1000 deleted Date objects requiring garbage collection hanging there that suddenly get all dumped together, and while your computer lags you wonder what is happening. :) by FrancescoMM, 06.07.2017 17:23
+0 for "and over 357 people voted that it's better" because we don't give votes for funny on SO. But +1 for good answer. And because it's funny. ;^) (I do get tired of "looks like a typo" complaints when it's a language feature. ~~ is a great truncate, but folks lodge the same complaint. But if it weren't there, someone'd invent it, you know? Learn the language, 357 people! It's fun.) by ruffin, 28.07.2017 18:01
In case you wonder about the logic of plus sign is: + is used as toInt() where it will neglect all the characters and return only numbers by Umair Riaz, 22.02.2021 10:35
Show remaining 10 comments

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();
11.05.2011 22:27
var time = || function() {
  return +new Date;

21.10.2008 10:05

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: /1000 |0

Warning: it might break in 2038 and return negative numbers if you do the |0 magic. Use Math.floor() instead by that time

Math.floor() solution:

Math.floor( /1000);

Some nerdy alternative by Derek 朕會功夫 taken from the comments below this answer:

new Date/1e3|0

Polyfill to get working:

To get it working in IE you could do this (Polyfill from MDN):

if (! { = 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 - 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 =;
    return function () {
        return - 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 / 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 follow this link: @ MDN

12.07.2012 07:15
var timestamp = Number(new Date()); // current time as number
21.10.2008 13:00

jQuery provides its own method to get the timestamp:

var timestamp = $.now();

(besides it just implements (new Date).getTime() expression)


15.03.2013 14:19

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;
21.09.2012 19:12

In addition to the other options, if you want a dateformat ISO, you can get it directly

console.log(new Date().toISOString());

29.01.2016 15:08

console.log(new Date().valueOf()); // returns the number of milliseconds since the epoch

30.04.2009 16:53

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:; //return 1495255666921

In MDN it's mentioned as below:

The 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

If you using a version below ES5,; not works and you need to use:

new Date().getTime();
20.05.2017 04:49


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


  • Solution (E) is fastest on Chrome and Safari and second fast on Firefox and this is probably best choice for fast cross-browser solution
  • Solution (G), what is surprising, is more than 100x faster than other solutions on Firefox but slowest on Chrome
  • Solutions C,D,F are quite slow on all browsers

enter image description here


Results for chrome

enter image description here

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() {

function F() {
  return Number(new Date());

function G() {
  // this solution returns time counted from loading the page.
  // (and on Chrome it gives better precission)


log = (n,f) => console.log(`${n} : ${f()}`);

This snippet only presents code used in external benchmark

27.06.2018 16:33

One I haven't seen yet

Math.floor( / 1000); // current time in seconds

Another one I haven't seen yet is

var _ = require('lodash'); // from here;
31.03.2014 08:18

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;


14.10.2015 16:41

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.

03.05.2012 09:02

I highly recommend using moment.js. To get the number of milliseconds since UNIX epoch, do


To get the number of seconds since UNIX epoch, do


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>

For more details, including other ways of installing and using MomentJS, see their docs

14.07.2015 08:29

For a timestamp with microsecond resolution, there's

function time() { 
  return + performance.timing.navigationStart;

This could for example yield 1436140826653.139, while only gives 1436140826653.

06.07.2015 00:01

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())));
21.05.2013 09:22
@b123400 - Here's the Lisp version: (new (chain (-date) (to-i-s-o-string))). by Inaimathi, 24.08.2013 03:17

You can only use

    var timestamp = new Date().getTime();

to get the current timestamp. No need to do anything extra.

16.03.2016 05:45

// The Current Unix Timestamp
// 1443534720 seconds since Jan 01 1970. (UTC)

// seconds
console.log(Math.floor(new Date().valueOf() / 1000)); // 1443534720
console.log(Math.floor( / 1000)); // 1443534720
console.log(Math.floor(new Date().getTime() / 1000)); // 1443534720

// milliseconds
console.log(Math.floor(new Date().valueOf())); // 1443534720087
console.log(Math.floor(; // 1443534720087
console.log(Math.floor(new Date().getTime())); // 1443534720087

// jQuery
// seconds
console.log(Math.floor($.now() / 1000)); // 1443534720
// milliseconds
console.log($.now()); // 1443534720087
<script src=""></script>

29.09.2015 13:55

Any browsers not supported, you can use this for get current date time:

currentTime = || +new Date()
09.05.2013 06:53
(Rephrasing my comment) Your code has a problem: it executes method instead of checking its support first. On older browsres it will cause is not a function error. by Salman A, 07.05.2015 09:18
Perhaps a better alternative would be to use a ternary operator to assert that actually exists (and is a function), before attempting to invoke it: currentTime = typeof === "function" ? : +new Date(). by mgthomas99, 04.04.2018 14:54

If it is for logging purposes, you can use ISOString

new Date().toISOString()


18.05.2019 20:43
time = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);
11.11.2009 11:38
This is wrong. The getTime() method already returns the number of milliseconds since the UNIX epoch, so this calculation will actually screw things up. by Skone, 16.06.2011 20:06
@Skone technically nothing is screwed up. Date.UTC(1970,0,1) will always evaluate to 0, no matter what time zone the user is in. still, I'd say this is a bad answer because of it. by Kip, 29.08.2011 17:17
@Kip Good point. We're both getting at the same thing though, the additional arithmetic here is unnecessary. by Skone, 21.09.2011 16:00
@Kip -- if someone ever got stupid and decided the Epoch needs to be "changed" ("broken" would be the proper word ...), that would work. Fortunately, no one is likely to ever get that stupid. by Julie in Austin, 04.07.2012 15:09
If the Epoch changes, the definition of Unix Timestamp changes. That makes the above code backwards compatible, but broken :) by Peter, 13.04.2013 13:22
The last 3 digits are unnecessary, so this answer is good :) by shahzain ali, 24.07.2017 06:00
Show remaining 1 comments

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.

29.05.2015 13:40

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;
11.03.2015 09:52
I was about to write the new Date() Object .You can console log(new Date()) and then skim through the related methods under the new Date() object/ function by sg28, 18.01.2018 00:38

This seems to work.

// returns 1444356078076

//returns 10/8/2015 21:02:16

console.log(clock.format( + clock.add(10, 'minutes'))); 
//returns 10/8/2015 21:08:18

var clock = {,
    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);
09.10.2015 02:03

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();
01.07.2013 06:47

For lodash and underscore users, use

var timestamp =; // in milliseconds
30.03.2015 08:40

Moment.js can abstract away a lot of the pain in dealing with Javascript Dates.


06.03.2015 00:33
Note that this gives the number of seconds (not milliseconds) since UNIX epoch. If you want the milliseconds, use moment().valueOf(). See my answer. by FullStack, 14.07.2015 08:33

more simpler way:

var timeStamp=event.timestamp || new Date().getTime();
26.10.2013 03:51
Do know where event comes from. You need to give a better explanation of the way you resolve it instead of you writing an answer. Please! by alexventuraio, 22.09.2016 22:54
I was about to write the new Date() Object .You can console log(new Date()) and then skim through the related methods under the new Date() object/ function by sg28, 18.01.2018 00:37

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:

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 = (! ? +new Date() :;

This will return the milliseconds since epoch time, of course, not seconds.

MDN Documentation on

14.12.2017 10:09

sometime I need it in objects for xmlhttp calls, so I do like this.

timestamp : parseInt(new Date().getTime()/1000, 10)
24.04.2014 06:46
Even shorter: new Date().getTime()/1000|0 but its slow and dirty by EaterOfCode, 26.09.2014 13:53
I was about to write the new Date() Object .You can console log(new Date()) and then skim through the related methods under the new Date() object/ function by sg28, 18.01.2018 00:37
var d = new Date();
13.04.2015 08:29
I was about to write the new Date() Object .You can console log(new Date()) and then skim through the related methods under the new Date() object/ function. the new Date().getTime() method will give you the time in the EPOCH format which can be interpreted if necessary by sg28, 18.01.2018 00:38

var my_timestamp = ~~(;

26.03.2015 19:47
Why downvote? ~~ is same parseInt .. nice bad school by KingRider, 31.10.2016 14:38

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.

27.03.2015 11:43

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(); = [
        pad(timestamp.getMonth() + 1), // getMonth() returns 0 to 11.

    timestamp.time = [
    ]; = parseInt("") + timestamp.time.join(""));
22.05.2014 21:00

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;

to directly get the timestamp without having to create a new Date object.

To return the required timestamp

new Date("11/01/2018").getTime()
26.11.2019 04:33
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())));
28.03.2018 05:22

there are many ways to do it. 
 new Date().getTime() 
 new Date().valueOf()

To get the timestamp in seconds, convert it using:

Math.floor( / 1000)
22.01.2021 15:54

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();
02.03.2020 13:30