Get date and month from date
The date object get method also helps in creating any kind of date format like
Basic Syntax of Date
First, we declare a variable date and using let keyword and assign a date object to it with the date “2020-10-15“.
let date = new Date("2020-10-15");
In the next step, we get the Date detail from the date object using the getDate() method and check its value using the console log.
Now, we also getting the month of date using getMonth() method.
Any idea, what should be the output of above code statements.
Here is the full code snippet for you to solve.
let date = new Date("2020-10-15"); console.log(date.getDate()); // output => ? console.log(date.getMonth()); // output => ?
Now, you know the answer is 15, 9. But why, doesn’t month value should be 10. Let me explain.
So, for getDate() method it give 25 which is clearly visible in date which pass to Date(“2020-10-15”).
But for getMonth() method always give one value less. That means, if you pass a date with month (10) “2020-10-15″.
Then it will give 9. Here is a solution snippet.
let date = new Date("2020-10-15"); console.log(date.getDate()); // output => 15 console.log(date.getMonth()); // output => 9
At last, That’s why we get an answer “15, 9“.
Let me know in the comment section, what you think about it.
I hope you understand the concept and logic behind it.
But wait, i have something more for you –
- JS Quiz – Math random in if condition
- JS Quiz – three dots with string variable will expand
And last but not the least, don’t forget to like, comment and share. It gives us a morale boost to remain to continue. Also, join our Facebook Page
If you have any questions, please feel free to ask me in the comment section and also let me know if you have any suggestions. As suggestions are always welcome.