By pupeno


2008-10-21 09:29:33 8 Comments

How can I get a timestamp in JavaScript?

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.

30 comments

@cenkarioz 2019-05-18 20:43:00

If it is for logging purposes, you can use ISOString

new Date().toISOString()

"2019-05-18T20:02:36.694Z"

@Alireza 2017-05-20 04:49:21

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

@ashish 2019-01-28 06:05:18

new Date().getTime(); and Date.now();

>> Return current timestamp

new Date("11/01/2018").getTime()

>> Return required timestamp

@Vineeth Sai 2019-01-28 07:43:41

Add some explanation along with your code.

@Kamil Kiełczewski 2018-06-27 16:33:13

Today - 2018.06.27 I provide some time comparison for pure js solutions. This can be useful for people who wanna get/measure time in JS in light/efficient way (eg. for real-time applications like simulations, games etc.)

Tested on MacOs High Sierra 10.13.3 on Chrome 67.0.3396.99 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit). On below screenshot I show you results for fastest browser (Safari):

enter image description here

As I observe the Date.now() was fastest method to get timestamp for all three browsers. Safari has 19.2M operations per second, Firefox 16.1M, Chrome 7.8M.

The new Date()*1 was slowest for Chrome (2.8M) and Firefox (2.6M). The Number(new Date()) was slowest for Safari (2.9M).

So the winner JS code is Date.now() and fastest browser is Safari (2x faster that chrome! ).

You can perform test on your machine here: https://jsperf.com/timestamp-test-x.

@daveb 2008-10-21 09:32:32

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).

Details:

On almost all current browsers you can use Date.now() 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 (!Date.now) {
    Date.now = function() { return new Date().getTime(); }
}

To get the timestamp in seconds, you can use:

Math.floor(Date.now() / 1000)

Or alternatively you could use:

Date.now() / 1000 | 0

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

I would recommend using Date.now() (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()

Timestamp in Milliseconds

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

@Milan Babuškov 2015-01-16 17:33:09

Another notable exception is node.js. I came here from Google looking to do the same in node

@gengkev 2015-05-03 07:03:17

Won't Date.now() / 1000 | 0 suffer from the Year 2038 problem? new Date('Jan 1, 2039') / 1000 | 0 == -2117514496

@code ninja 2015-05-19 15:23:48

or even, w/o using Math.floor.. ~~(Date.now() / 1000)

@Josh1billion 2015-10-22 22:15:51

Does V8 optimize Math.floor()? Noting the bitwise approach you provided, it seems like it'd be a trivial thing for a compiler to optimize, given all the much trickier optimizations they've already pulled off. But even if it doesn't, I'd still use the approach that's most readable.

@GottZ 2015-10-29 07:17:25

@Josh1billion thats why i dislike such edits: stackoverflow.com/revisions/221297/6 anyways.. you should never do micro benchmarks. it does not really matter.

@GottZ 2015-10-29 07:21:22

@gengkev yes it might break 2038.

@Basilin Joe 2016-01-01 12:01:25

Can timestamp be used as a unique id

@Lukas 2016-01-18 09:00:20

@CodeBean UNIX timestamp is unique for 1 second i would at least add some random hash as prefix and/or suffix.

@OrangeDog 2016-04-04 13:08:07

@MilanBabuškov but node.js does support Date.now()

@Harry Sadler 2017-03-29 19:06:36

While +new Data is clever, it isn't readable by other devs. Date.now() is clearer and ensures everyone else knows what's going on.

@Matthieu Charbonnier 2017-06-28 07:56:42

new Date() give me Wed Jun 28 2017 09:53:45 GMT+0200 (Paris, Madrid (heure d’été)) in Chrome. You need to use Date.now()

@Benny Jobigan 2018-10-23 03:00:09

@gengkev According to the ecmascript spec It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC. It also says the "actual" range is ±100,000,000 days, which is still about ±274,000 years. So I should think we'll be ok in 2038.

@gengkev 2018-10-23 05:59:51

@BennyJobigan Yes, but the |0 operation coerces to a 32-bit integer first. So the range of numbers for that is much smaller.

@Benny Jobigan 2018-10-23 11:12:55

@gengkev gotcha. I didn't realize you were talking about that one specific case.

@stomy 2018-11-06 00:07:40

To store in a variable use var t = + new Date();

@stomy 2019-05-15 17:22:39

+ new Date() + ' ' + Date.now() + ' ' + new Date().getTime() + ' ' + new Date().valueOf() Test this code and you'll see that they are all the same.

@Belldandu 2014-03-31 08:18:48

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

@GottZ 2014-12-17 13:55:34

Date.now() /1000 |0 does the same and has been answered before

@GottZ 2014-12-21 14:16:19

well. i sure edited Math.floor() into it but only to make clear that it has the same effect as |0. i did not want to hurt you or anything. i just wanted to tell you that your answer in some kind of way already exists. by looking at all given answers there are some that notice floor in some way.

@mgthomas99 2018-04-04 15:03:18

I think importing the entire Lodash library just to use _.now() is a little bit overkill. I would recommend only importing the Lodash functionality you need to use (in this case, _.now() on NPM), but even they have deprecated their package in favour of just using Date.now().

@GottZ 2012-07-12 07:15:09

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. Use Math.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

@GottZ 2012-08-24 06:53:27

|0 is similar to Math.floor() since it is a bit operation (that does not work with floats). usualy its even faster than Math.floor() since it is not a function call, it is a native javascript operator.

@Web_Designer 2013-03-16 02:36:33

@GottZ 2013-09-16 09:58:00

@Christophe why do you think that? because of the IE fix? except that part its pretty simple and customizable i think.

@rlemon 2013-09-24 20:35:38

polyfills / shims are not complicated. They are a result of having to support 9 different browser versions and the industry deciding to choose which standards they adopt and which they just make up.

@rlemon 2013-09-24 20:46:28

but for an example of over complicated: !('now' in Date) && (Date.now = (function() { var d = new Date(); return d.getTime.bind(d); }())); note: this shims the code with bind, which would need to be shimmed :P yes it is silly. shhhh

@Derek 朕會功夫 2014-11-15 02:11:08

For reference the most compact you can get is new Date/1e3|0.

@unknown123 2018-03-28 05:22:44

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())));
}

@Valentin 2015-10-14 16:41:30

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;

console.log(ts);

@dchest 2016-02-07 17:08:23

Yeah, don't minify code manually, especially to save 1 byte.

@Valentin 2016-09-24 03:39:05

@dchest "Math.floor(new Date().getTime()/1000)".length == 37; "new Date/1E3|0".length == 14; 37 -14 = 23 bytes;

@Matthieu Charbonnier 2017-10-25 07:51:22

A great way to make your code unreadable...

@Valentin 2017-10-27 03:03:20

@MatthieuCharbonnier What exactly is unreadable? Division sign, 1E3, pipe or zero? Please see the code snippet in my answer above.

@Matthieu Charbonnier 2017-10-29 07:58:21

@Valentin You are minifying/complicating simple code for almost no benefits. I don't see the point to do that. We are not on Code Golf!

@Valentin 2017-10-30 18:17:17

@MatthieuCharbonnier, There is nothing complicated, just basic syntax and operators. The main point is to write short, clear and understandable code.

@Matthieu Charbonnier 2017-10-31 08:46:12

@Valentin Please explain me how replacing Math.floor() by |0 is making this code "clear and understandable". Explain me what is the point to save 1 byte by replacing 1000 by 1E3. This is ridiculous. I see bad code.

@Valentin 2017-10-31 16:15:49

@MatthieuCharbonnier, As I said above, this is the basic syntax. Do you use new Array() instead of just [] or do you use new Object() instead of {}? Many people - many opinions. We are prefer to use short alternatives.

@Olemak 2017-12-14 10:09:55

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.

MDN Documentation on Date.now

@xer0x 2011-02-18 00:33:44

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

@inanutshellus 2012-10-29 15:51:23

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.

@inanutshellus 2013-07-08 12:44:19

@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!

@Jason T Featheringham 2013-07-18 01:58:54

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.

@Niklaus 2013-09-17 10:38:06

Not useful. This returned a time string (as in "Sat 14th...") when doing var foo = 'NEW-' + new Date;

@kirb 2013-10-02 11:50:18

@Niklaus That's because you're concatenating it to another string. In that case, new Date().toString() is called.

@Abuzzy 2014-12-19 10:47:52

out of curiosity what is the +operator doing to make it come out like a string?

@ansiart 2014-12-20 22:58:16

+ 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.

@Rimian 2015-03-12 10:40:01

If it were covered by unit tests, it wouldn't be such a problem.

@1j01 2015-03-17 19:42:19

@Niklaus in that case you would need another plus to act as the unary operator: 'NEW-' + +new Date

@Marcus Johansson 2016-09-04 08:56:34

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.

@xer0x 2016-09-08 20:43:47

@MarcusJohansson people should be using Date.now() if they are using a newer browser like Chrome. I tried this in Chrome 52 and Chrome Canary 55 and +new Date still worked.

@xer0x 2017-01-04 00:15:00

@FelixGagnon-Grenier I added Date.now() 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.

@FrancescoMM 2017-07-06 17:23:03

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. :)

@ruffin 2017-07-28 18:01:47

+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.)

@Umopepisdn 2018-08-16 19:48:02

If your only issue with this is readability and similarity to a typo, write it like +(new Date).

@Clain Dsilva 2019-02-05 04:53:01

nobody explained why Date.now() is bad

@Joaquinglezsantos 2016-01-29 15:08:36

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

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

@Alex Ventura 2016-09-22 23:01:57

It does not return an integer with the question is asked for!

@Joaquinglezsantos 2017-05-04 07:19:53

@AlexVentura with an string dateformat ISO you can instantiate an date object and subtract between them. For example: new Date("2017-05-04T07:11:28.940Z") - new Date("2017-05-04T07:11:14.092Z")

@Tom Viner 2009-04-30 16:53:52

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

@Kenan Sulayman 2011-11-01 20:01:22

This equals +new Date.. :)

@Orlando 2013-05-20 22:12:36

just do Date.now()

@Christophe 2013-09-14 16:49:01

@Orlando see the other answers, the issue with now() is browser support

@Orlando 2013-09-14 16:52:02

@Christophe just do a simple polyfill, developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

@Christophe 2013-09-14 16:53:36

@Orlando exactly, don't just do Date.now()

@Orlando 2013-09-14 16:53:53

@Christophe Date.now() is faster than Date().valueOf().. jsperf.com/new-date-vs-date-now-vs-performance-now/6 so is better if you just use a polyfill when is not available.

@cincodenada 2014-03-19 00:48:48

@apx: It equals it sure, but valueOf() is clearer and less confusing.

@Jitendra Pawar 2016-03-16 05:45:22

You can only use

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

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

@blueberry0xff 2015-09-29 13:55:41

// 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(Date.now() / 1000)); // 1443534720
console.log(Math.floor(new Date().getTime() / 1000)); // 1443534720

// milliseconds
console.log(Math.floor(new Date().valueOf())); // 1443534720087
console.log(Math.floor(Date.now())); // 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="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

@Ron Royston 2015-10-09 02:03:25

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);
            }
};

@KingRider 2016-10-31 14:42:08

nice advanced scripts, good jobs!

@FullStack 2015-07-14 08:29:56

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

@iter 2015-07-06 00:01:55

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.

@Kevin Leary 2015-05-29 13:40:52

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.

@Salman A 2012-05-03 09:02:16

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.

@Ry- 2012-05-30 05:01:49

You don't need the parentheses: new Date().getTime() / 1000

@johndodo 2012-09-18 07:10:27

You don't need them, but they make code more readable (IMHO). Matter of taste I guess.

@Derek 朕會功夫 2014-11-15 02:12:34

You don't even need () after new Date and .getTime() since / will cast the Date object into a number anyway.

@jameslouiz 2015-04-13 08:29:01

var d = new Date();
console.log(d.valueOf()); 

@sg28 2018-01-18 00:38:32

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

@Muhammad Reda 2015-03-30 08:40:23

For lodash and underscore users, use _.now.

var timestamp = _.now(); // in milliseconds

@user257319 2015-03-27 11:43:20

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.

@Eugene 2015-03-26 19:47:12

var my_timestamp = ~~(Date.now()/1000);

@Supersharp 2015-10-28 16:44:59

does it always work?

@KingRider 2016-10-31 14:38:49

Why downvote? ~~ is same parseInt .. nice bad school

@george 2015-03-11 09:52:48

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;

@sg28 2018-01-18 00:38:17

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

@Rimian 2015-03-06 00:33:36

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

@FullStack 2015-07-14 08:33:29

Note that this gives the number of seconds (not milliseconds) since UNIX epoch. If you want the milliseconds, use moment().valueOf(). See my answer.

@Saucier 2014-05-22 21:00:20

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);

@Staale 2008-10-21 10:05:36

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

time();

@Chris Noe 2008-10-22 00:58:58

Why the || operator? Is Date.now() not available on all browsers?

@Staale 2008-11-04 08:13:27

Apparently not, I found the code in modulejs

@Søren Løvborg 2011-07-14 18:54:59

Date.now() is from JavaScript 1.5, and is not supported on IE 8.

@Per Quested Aronsson 2012-10-04 07:21:16

Engines which have not been updated to support the Date.now method can work around the absence of it using the following shim: if (!Date.now) { Date.now = function now() { return +(new Date); }; }

@DevC 2014-04-24 06:46:40

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

timestamp : parseInt(new Date().getTime()/1000, 10)

@EaterOfCode 2014-09-26 13:53:17

Even shorter: new Date().getTime()/1000|0 but its slow and dirty

@sg28 2018-01-18 00:37: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

@Vicky Gonsalves 2013-10-26 03:51:22

more simpler way:

var timeStamp=event.timestamp || new Date().getTime();

@Salman A 2015-06-06 17:30:55

What is event?

@Alex Ventura 2016-09-22 22:54:34

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!

@sg28 2018-01-18 00:37:46

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

Related Questions

Sponsored Content

3 Answered Questions

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

26 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

44 Answered Questions

[SOLVED] How do I get the current date in JavaScript?

  • 2009-10-07 11:39:02
  • Suresh
  • 2256461 View
  • 1964 Score
  • 44 Answer
  • Tags:   javascript date

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5709475 View
  • 7100 Score
  • 79 Answer
  • Tags:   javascript arrays

14 Answered Questions

[SOLVED] Encode URL in JavaScript?

73 Answered Questions

[SOLVED] How can I convert a string to boolean in JavaScript?

  • 2008-11-05 00:13:08
  • Kevin
  • 1611536 View
  • 2142 Score
  • 73 Answer
  • Tags:   javascript

86 Answered Questions

[SOLVED] How do JavaScript closures work?

30 Answered Questions

[SOLVED] How to append something to an array?

23 Answered Questions

[SOLVED] How do you check if a variable is an array in JavaScript?

Sponsored Content