Warm tip: This article is reproduced from stackoverflow.com, please click
javascript

date = new Date();d.valueOf() vs Date.now()

发布于 2020-07-02 10:11:54

I am getting started with JavaScript. I consulted my colleague on how to get the current time.

He told me with this code:

> date = new Date()
> date.valueOf()

But most people do it this way:

> Date.now()

The second method is simpler and more readable.

If I want to convince my colleague to use the second one, how should I explain the difference to him?

Questioner
user5456386
Viewed
5
Bohuslav Burghardt 2015-10-17 16:15

There are several ways to get the current time in JavaScript:

As mentioned in the comments and MDN links, Date.now() is not supported in Internet Explorer 8. So if IE 8 compatibility is a concern you should use new Date().valueOf() at the cost of slightly diminished code readability.

Or if you want to use Date.now() but must be compatible with browsers which don't support it, you can place following code somewhere in your JavaScript files, which will add support for it.

if (!Date.now) {
    Date.now = function() {
        return new Date().getTime();
    }
}