Shruthi Bhaskar
Shruthi Bhaskar

Reputation: 1281

Why there is a difference in node js Date() object values in console.log()?

I am new to node and I was going through Date() object, values and Date format in Node. When I run the below code, I get different output in console.

const date_1 = new Date();
console.log(date_1);
const date_2 = new Date();
console.log(+date_2);
const date_3 = new Date();
console.log('comma:',date_3);
const date_4 = new Date();
console.log('plus:'+date_4);

gives the below output in console?

2018-02-01T06:55:41.327Z
1517468141327
comma: 2018-02-01T06:55:41.327Z
plus:Thu Feb 01 2018 12:25:41 GMT+0530 (India Standard Time)

Can someone let me know what I am missing here in terms of understanding.

Upvotes: 3

Views: 544

Answers (3)

Nir Levy
Nir Levy

Reputation: 4740

You are implicitly converting your date to something else:

const date_1 = new Date();
console.log(date_1); //prints date as a Date object
const date_2 = new Date();
console.log(+date_2); //converts date to a number
const date_3 = new Date();
console.log('comma:',date_3); //prints date as a Date object
const date_4 = new Date();
console.log('plus:'+date_4); //converts date to a String

Upvotes: 2

Rahul
Rahul

Reputation: 942

The value of new Date() is the universal format(Z) so when you log a date, It's value is logged.

console.log(date);
console.log('abc',date);

But when + operator with a number of just + is used it converts it to Number format(milliseconds in case of date) -

console.log(+date);
console.log(1+'a'); // NaN

And when you use + with a string, It gets toString() value of date which is Thu Feb 01 2018 12:45:21 GMT+0530 (IST)

console.log(date.toString()); // Thu Feb 01 2018 12:45:21 GMT+0530 (IST)

Upvotes: 2

deepak thomas
deepak thomas

Reputation: 1180

For the first and third case are displayed as default

new Date().toJSON()

For second case +new Date() unary operator, it's equivalent to:

function(){ return Number(new Date); }

For the fourth case 'plus:'+date_4, the string are concatenated as result the date is equivalent to

'plus:'+date_4.toString() 

Upvotes: 3

Related Questions