How to exclude Sundays between two dates in javascript

How to exclude Sundays between two dates in javascript

In this tutorial, we will learn how to exclude Sundays between two dates in javascript. This is a very important aspect of any web application because sometimes it is required while calculating the number of days at the time of taking leave for an employee in an organization.

Assuming if someone is creating a software application related to employee management system then it will be needed for sure.

Also read, How to calculate javascript difference between two dates in days

Illustration of how to exclude Sundays between two dates in Javascript with example

Before getting started we have to understand some methods in Javascript as given below

  • date()
  • getTime()
  • getDay()

date():- This function creates a new date object with the current date and time and displays the browser’s timezone as a string.

getTime():- This function returns the time as a number of milliseconds from January 1, 1970, to the currently specified date.

getDay():- This function returns the number representation of the days of the week from Sunday to Saturday ( 0 to 6 ).

Complete Code:-

<title>ajax example</title>

	<label for="start_date"><b>Start Date:</b></label><br><br>
	<input type="date" id="start_date"><br><br>
	<label for="end_date"><b>End Date:</b></label><br><br>
	<input type="date" id="end_date" onchange="getDays()"><br><br>
	<label for="sundays"><b>Total Sundays:</b></label><br><br>
	<input type="number" id="sundays"><br><br>
	<label for="days"><b>Total Days Without Sundays:</b></label><br><br>
	<input type="number" id="days"><br><br>

<script type="text/javascript">
	function getDays()
	  var from_date = new Date(document.getElementById('start_date').value);
	  var to_date = new Date(document.getElementById('end_date').value);
	  var start = new Date(from_date);
	  var finish = new Date(to_date);
	  var dayMilliseconds = 1000 * 60 * 60 * 24;
	  var weekendDays = 0;
	  while (start.getTime() <= finish.getTime()) {
	    var day = start.getDay();
	    if (day == 0) {
	    start = new Date(+start + dayMilliseconds);
	  var days = finish.getTime() - start.getTime();
	  document.getElementById('sundays').value = weekendDays;
	  document.getElementById('days').value = (days / (1000 * 3600 * 24))+1-(weekendDays);

Conclusion:- I hope this tutorial will help you to count the number of Sundays between two dates in javascript. If there is any doubt then please leave a comment below.

Leave a Comment