How to exclude Sundays between two dates in javascript

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

  • date()
  • getTime()
  • getDay()
<html>
<head>
<title>ajax example</title>
</head>
<body>
<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);
alert(start);
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) {
weekendDays++;
}
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);

}
</script>
</body>
</html>

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Bipsmedium

Bipsmedium

25 Followers

Hi, This is Biplab and I am web developer well versed in PHP and other open source technologies. I am here to share my experience with the community.