2

When i'm setting up date object using the below statement the output showing different in nodejs. Can you please help me to understand why it is like this. And how i need to pass to print right value.

var date1= new Date(2017,01,01);
var date2= new Date(2017,01,31);
console.log("2017-01-01 is printed as ==>",date1);
console.log("2017-01-31 is printed as ==>",date2);

Output

2017-01-01 is printed as ==> 2017-01-31T18:30:00.000Z

2017-01-31 is printed as ==> 2017-03-02T18:30:00.000Z

2 Answers 2

1

Printing your logs like this
console.log("2017-01-01 is printed as ==>"+date1); console.log("2017-01-31 is printed as ==>"+date2); will give you your expected logs It is because console log will take date as object of date while using comma and while using + it will apply object.toString() to date object.

Sign up to request clarification or add additional context in comments.

Comments

0

Month parameter starts from 0 (January) to 11 (December) so if you want to get 2017-01-01 you need to use:

var date1 = new Date(2017, 0, 1)

More info here: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Date

7 Comments

after doing your suggestion still it is print as same var date1= new Date(2017,0,1); var date2= new Date(2017,0,31); console.log("2017-01-01 is printed as ==>",date1); console.log("2017-01-31 is printed as ==>",date2); Output 2017-01-01 is printed as ==> 2016-12-31T18:30:00.000Z 2017-01-31 is printed as ==> 2017-01-30T18:30:00.000Z
can you try printing your logs like this console.log("2017-01-01 is printed as ==>"+date1); console.log("2017-01-31 is printed as ==>"+date2); ?
@TGW is there a difference? The logging with the comma appears to work the same.
@StevenTang using comma will pass this date1 and date2 as an object to the log method while using + will invoke object.toString on the date object and print the date. Hence such different behaviors. This discussion on stack might give you more explanation.
@TGW Could you please update this in answer section so that I can make this question as answered .
|

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.