Soatl
Soatl

Reputation: 10592

Convert Date.now() to Milliseconds in JavaScript

I am having a lot of trouble doing something that seems obvious. I have a date:

Date.now()

I want it in milliseconds from epoch. I cannot get that to work. I have tried:

Date.now().getTime();
(Date.now()).getTime();
Date.now().getMilliseconds();
(Date.now()).getMilliseconds();

var date = Date.now();
var ms = date.getTime();
var ms = date.getMilliseconds();

All of these fail because apparently getTime() and getMilliseconds() (which I don't think is the correct approach anyways) are apparently not functions.

What am I doing wrong here?

Upvotes: 16

Views: 25638

Answers (2)

Jonathan
Jonathan

Reputation: 9151

Date.now() already returns ms from epoch, not a Date object...

Date.now is a method in the Date namespace1, same as Math.random is for Math.
Date (unlike Math) is also a constructor. Used like new Date(), it will return a Date object.

1. A property of Date, which is a function/object

Upvotes: 13

Jeremy Banks
Jeremy Banks

Reputation: 129746

You already have the value you want.

var numberOfMillisecondsSinceEpoch = Date.now();

You're attempting to call methods on a Date object, such as you'd get for the current date by calling new Date(). That's not necessary or appropriate if you're using Date.now(), which returns a number instead.

For platforms that don't provide Date.now(), you can convert the current Date object to a number to get the same value.

var numberOfMillisecondsSinceEpoch = Number(new Date());
Number(new Date()) === Date.now() // if your system is quick enough

Upvotes: 9

Related Questions