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?
This is the number of seconds since the 1970 epoch. To convert seconds to milliseconds, you need to multiply the number of seconds by 1000. To convert a Date to milliseconds, you could just call timeIntervalSince1970 and multiply it by 1000 every time.
JavaScript - Date getMilliseconds() Method Javascript date getMilliseconds() method returns the milliseconds in the specified date according to local time. The value returned by getMilliseconds() is a number between 0 and 999.
Date. now() returns the number of milliseconds since January 1, 1970.
It is used to work with dates and times. The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With