0

I have been working with dates and realized these 2 commands Date(d.getTime()) and new Date(d.getTime()) are different.

When I run this snippet:

        var d = new Date(2016,11,12);
        console.log(Date(d.getTime()));
        console.log(new Date(d.getTime()));

I have this result:

(index):68 Thu Dec 12 2019 18:02:41 GMT-0300 (Horário Padrão de Brasília)
(index):69 Mon Dec 12 2016 00:00:00 GMT-0200 (Horário de Verão de Brasília)

Why are they different?

I have tried to find some answers but I find none. These are some of references I have gone through:

Difference between Date(dateString) and new Date(dateString)

Why we can't call methods of Date() class without new operator

http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.2

Diogo Bratti
  • 115
  • 1
  • 8

2 Answers2

2

Date gets the window/global Date object, new Date() creates a new static Date object. When you create a new Date() you are freezing its value in time.

When you use Date(), it returns a string representation of the current date as if calling new Date().toString().

Based on your code:

// this is a new date, Dec. 12, 2016
var d = new Date(2016,11,12);  

// this returns the time value of Date d
d.getTime()

// Calling Date as a function just returns a string for
// the current date, arguments are ignored
console.log(Date(d.getTime())); 

// this creates a new date based on d's time value
console.log(new Date(d.getTime()));
RobG
  • 142,382
  • 31
  • 172
  • 209
selfagency
  • 1,481
  • 1
  • 9
  • 12
0
Salman A
  • 262,204
  • 82
  • 430
  • 521