3

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.

3 Answers 3

3

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() 
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.