JavaScript provides built-in Date methods to retrieve the day and month from a date. The getDay() method returns the day as a number, while getMonth() returns the month as a zero-based number.
- Use new Date() to create a Date object for the current date.
- Use getDay() to get the day of the week and map it to its name.
- Use getMonth() to get the month and map it to its name.
Approach 1: Using getDay() and getMonth() Methods
The getDay() method returns the day of the week as a number from 0 to 6, where 0 represents Sunday and 6 represents Saturday. Similarly, getMonth() returns a number from 0 to 11, where 0 represents January and 11 represents December. These values can be mapped to arrays containing the corresponding day and month names.
Example: Get the current day and month using getDay() and getMonth() methods.
<body>
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP">
</p>
<button onclick="GFG_Fun()">
Click Here
</button>
<p id="GFG_DOWN">
</p>
<script>
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
el_up.innerHTML = "Click on the button to get "
+ "the day and month of the date.";
var Days = ['Sunday', 'Monday', 'Tuesday',
'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var Months = ['January', 'February', 'March', 'April',
'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'];
var currentDay = new Date();
// Get the current day name
var day = Days[currentDay.getDay()];
// Get the current month name
var month = Months[currentDay.getMonth()];
function GFG_Fun() {
el_down.innerHTML = "Day - " + day
+ ",<br> Month - " + month;
}
</script>
</body>
Approach 2: Using getDay() and getMonth() to Get Numeric Values
Instead of mapping the returned values to names, we can directly use getDay() and getMonth() to obtain the numeric representation of the day and month.
Example: Get the current day and month as numeric values.
<body style="text-align:center;">
<h1 style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style=
"font-size: 19px; font-weight: bold;">
</p>
<button onclick="GFG_Fun()">
Click Here
</button>
<p id="GFG_DOWN" style=
"color: green; font-size: 24px; font-weight: bold;">
</p>
<script>
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
el_up.innerHTML = "Click on the button to get the "
+ "day and month of the date.";
var currentDay = new Date();
// Get the current day as a number
var day = currentDay.getDay();
// Get the current month as a number
var month = currentDay.getMonth();
function GFG_Fun() {
el_down.innerHTML = "Day - " + day +
" (Sunday is 0),<br> Month - "
+ month + " (January is 0).";
}
</script>
</body>