Jessica Illy
Jessica Illy

Reputation: 67

set date with year confusion in javascript Date()

According to w3schools :

There are 4 ways of initiating a date:

new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

so when I try console.log(new Date(2015)); it gave me 1970-01-01T00:00:02.015Z ?

Upvotes: 0

Views: 50

Answers (3)

Leticia
Leticia

Reputation: 76

It thinks that 2015 is the amount of milliseconds you want.

You could try using a calculator to see how many milliseconds the year 2015 is equivalent to, but it would be bad to maintain.

You should use one of the other ways you listed:

new Date(dateString)

new Date('01/01/2015')

or

new Date(year, month, day, hours, minutes, seconds, milliseconds)

new Date(2015,0,1)

Upvotes: 1

germanfr
germanfr

Reputation: 562

You initialized it with a number, which actually means milliseconds or new Date(milliseconds).

Alternatively, you can do this:

console.log(new Date('01/01/2015'));

If what you want is the current time or year, you can get it with

var now = new Date();
console.log(now.getFullYear());

Finally, I recommend you to read MDN entries which are more accurate than W3Schools'.

Upvotes: 0

nikjohn
nikjohn

Reputation: 21850

The syntax is:

console.log(new Date(milliseconds)

The docs on MDN state clearly:

Creates a JavaScript Date instance that represents a single moment in time. Date objects are based on a time value that is the number of milliseconds since 1 January, 1970 UTC.

Upvotes: 0

Related Questions