;

How to Get The First Day and Last Day of the Month using Jquery and Javascript


Tutorialsrack 28/04/2019 Jquery Javascript

In this article, we will learn about how to get the first day and last day of the month using Jquery and Javascript.

To get the current date using jquery, we use date() function:

Example - To get the current date using jquery
var date = new Date();

To get the year of the given date using jquery, we use getFullYear() function:

Syntax - of SELECT Statement
var year = date.getFullYear();

To get the month of the given date using jquery, we use getMonth() function:

Syntax - of SELECT Statement
var month = date.getMonth();

Once I get the month and year for selected or given date, now I need to get the first and last day of the month. Again I am using the Date() method twice to get the desired output.

Example - To Get The First And Last Day Of The Month
var firstDay = new Date(year, month, 1);
var lastDay = new Date(year, month + 1, 0);

In both the above methods, I am passing 3 parameters each, and the first 2 parameters are year and month and the third parameter indicates the day.

 In the first method, the third parameter indicates the day (day one), and it will return the first day of the month.

And the second method is a little bit tricky. I have assigned + 1 to the month and 0 for the day. This will return the last day of the month.

For example, if we select a date for the month of April, adding + 1 would return 4, that is, May. However, adding 0 for the day would return 4, since there is no 0 day for the month of June.

Here is the complete code to Get The First Day and Last Day of the Month using Jquery and Javascript:

Example - Get The First Day and Last Day of the Month
<!DOCTYPE html>
<html>
<head>
<title>How to Get The First Day and Last Day of the Month using Jquery and Javascript </title>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>

var date = new Date();
var year = date.getFullYear();

var month = date.getMonth();

var firstDay = new Date(year, month, 1);

var lastDay = new Date(year, month + 1, 0);
document.write("<h2>Get The First Day and Last Day of the Month using Jquery or javascript</h2>");
document.write("<b>First Day of Month:-</b> "+firstDay);
document.write("<br/><b>Last Day of Month:-</b> "+lastDay);
</script>

</head>
<body>
</body>
</html>

I hope this article will help you to understand how to get the first day and last day of the selected month using Jquery and Javascript.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags