378

Possible Duplicate:
How do you get a timestamp in JavaScript?
Calculating milliseconds from epoch

How can I get the current epoch time in Javascript? Basically the number of milliseconds since midnight, 1970-01-01.

Community
  • 1
  • 1
antonpug
  • 13,724
  • 28
  • 88
  • 129
  • 14
    Note that this question (and some duplicates) ask for milliseconds since epoch. While JavaScript gives you this, note that standard Unix epoch is usually expression in seconds (1/1000 the value you get from JS). – Phrogz Mar 05 '12 at 23:48
  • 25
    `new Date/1E3|0` - instantiate `Date`, coerce to number, divide by 1000 and floor. – Camilo Martin Dec 15 '12 at 04:13
  • 3
    @CamiloMartin You should write this an an answer. It's the best. – Justin Noel Nov 25 '14 at 14:26
  • 4
    @Justin Thanks! But note that, since I wrote that, IE8 has become the kind of browser that you may be ready to say "no" to. If you're ready to discard IE8 support, use this: `Date.now()` (easily shimmable otherwise). – Camilo Martin Nov 25 '14 at 23:51

2 Answers2

675

Date.now() returns a unix timestamp in milliseconds.

const now = Date.now(); // Unix timestamp in milliseconds
console.log( now );

Prior to ECMAScript5 (I.E. Internet Explorer 8 and older) you needed to construct a Date object, from which there are several ways to get a unix timestamp in milliseconds:

console.log( +new Date );
console.log( (new Date).getTime() );
console.log( (new Date).valueOf() );
Paul
  • 139,544
  • 27
  • 275
  • 264
85

This will do the trick :-

new Date().valueOf() 
Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
raina77ow
  • 103,633
  • 15
  • 192
  • 229
  • 1
    Did you get the parenthesis wrong? Check out this (rejected) [edit suggestion](http://stackoverflow.com/review/suggested-edits/14668514) from MarkHu. – Nisse Engström Dec 22 '16 at 04:33
  • 7
    No, it's working; you can check [this great answer](http://stackoverflow.com/a/36597316/1229023) explaining the reasons. BTW, this expression can be simplified up to `+new Date` - for the same reasons. – raina77ow Dec 22 '16 at 21:43
  • This would bomb out in php where you would need to do `(new DateTime)->format('U')` but js is ok without the parens – chiliNUT Aug 29 '17 at 02:38