Wen
Wen

Reputation: 1220

Which to use in oder to get current time in javascript, Date() or new Date()?

If I am passing current time as an argument to function, which way is correct, Date() or new Date()? Take the following code for example, which one is better?

function logTime(time) {
    console.log(time);
}

//One
var now = new Date();
logTime(now);

//Two
logTime(new Date());

//Three
logTime(Date());

Upvotes: 2

Views: 233

Answers (3)

yckart
yckart

Reputation: 33398

At the first, the new operator is essential if you need something from its properties. Read the note-block here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

... to the caching-thing: it makes no sense to store it in a variable, since you just need the timestamp.

Upvotes: 0

Pik'
Pik'

Reputation: 7077

It's probably better to use new Date, because you then get a real Date object.

> var d = Date();
undefined
> d
'Thu Aug 01 2013 02:22:19 GMT+0200 (CEST)'
> typeof d
'string'

Date, when used as a normal function, returns a String. When used as a constructor, it returns an object having the Date prototype, thus you can use the methods getTime, getSeconds etc.

> d = new Date();
Thu, 01 Aug 2013 00:24:41 GMT
> typeof d
'object'
> d.getTime();
1375316681520
> d.getSeconds();
41

Upvotes: 5

Samer
Samer

Reputation: 988

Date() will only output the timestamp

new Date() will return an instance of Date which you can use to call it's functions. It's more useful with the new when you are passing arguments to set a date manually.

Upvotes: 2

Related Questions