Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Date.now() to Milliseconds in JavaScript

Tags:

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?

like image 338
Soatl Avatar asked Apr 20 '16 20:04

Soatl


People also ask

How do you convert Date to milliseconds?

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.

How do you write milliseconds in JavaScript?

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.

Is today a millisecond Date?

Date. now() returns the number of milliseconds since January 1, 1970.

What is new Date () in JavaScript?

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.


2 Answers

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

like image 91
Jonathan Avatar answered Oct 08 '22 11:10

Jonathan


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
like image 8
Jeremy Avatar answered Oct 08 '22 13:10

Jeremy