How to count the number of sundays between two dates - javascript

I tried the JS below:
var start = new Date("25-05-2016");
var finish = new Date("31-05-2016");
var dayMilliseconds = 1000 * 60 * 60 * 24;
var weekendDays = 0;
while (start <= finish) {
var day = start.getDay()
if (day == 0) {
weekendDays++;
}
start = new Date(+start + dayMilliseconds);
}
alert(weekendDays);
However, it gives the wrong output.
I need to get the total count of Sundays between the two dates.

You use incorrect date format.It will work if init date so:
var start = new Date("2016-05-25");
var finish = new Date("2016-05-31");

Your date format is wrong. Dates' string format is "yyyy-mm-dd". See here for more information.
Also, looping each day of the interval is very inefficient. You may try the following instead.
function getNumberOfWeekDays(start, end, dayNum){
// Sunday's num is 0 with Date.prototype.getDay.
dayNum = dayNum || 0;
// Calculate the number of days between start and end.
var daysInInterval = Math.ceil((end.getTime() - start.getTime()) / (1000 * 3600 * 24));
// Calculate the nb of days before the next target day (e.g. next Sunday after start).
var toNextTargetDay = (7 + dayNum - start.getDay()) % 7;
// Calculate the number of days from the first target day to the end.
var daysFromFirstTargetDay = Math.max(daysInInterval - toNextTargetDay, 0);
// Calculate the number of weeks (even partial) from the first target day to the end.
return Math.ceil(daysFromFirstTargetDay / 7);
}
var start = new Date("2016-05-25");
var finish = new Date("2016-05-31");
console.log("Start:", start);
console.log("Start's week day num:", start.getDay());
console.log("Finish:", finish);
console.log("Finish's week day num:", finish.getDay());
console.log("Number of Sundays:", getNumberOfWeekDays(start, finish));

Your date format and comparison condition should change like the following:
var start = new Date("2016-05-11");
var finish = new Date("2016-05-31");
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);
}
alert(weekendDays);
Check Fiddle

You are using incorrect date format.
Just Change the format to:
var start = new Date(2016, 4, 25);
var finish = new Date(2016, 4, 31);

Try this function:
function CalculateWeekendDays(fromDate, toDate){
var weekendDayCount = 0;
while(fromDate < toDate){
fromDate.setDate(fromDate.getDate() + 1);
if(fromDate.getDay() === 0){
++weekendDayCount ;
}
}
return weekendDayCount ;
}
console.log(CalculateWeekendDays(new Date(2011, 6, 2), new Date(2011, 7, 2)));
This will give you number of sunday come between 2 dates

change your date format.It will work
var start = new Date("05-16-2016");
var finish = new Date("05-31-2016");
var dayMilliseconds = 1000 * 60 * 60 * 24;
var weekendDays = 0;
while (start <= finish) {
var day = start.getDay()
if (day == 0) {
weekendDays++;
}
start = new Date(+start + dayMilliseconds);
}
console.log(weekendDays);

JS date format doesn't have "dd-MM-yyyy" ,so it will invalid date format .Try recreate date is ok or just change your date format Date Format
Try this:
var start = new Date("25-05-2016");
var end = new Date("31-05-2016");
var startDate = new Date(start);
var endDate = new Date(end);
var totalSundays = 0;
for (var i = startDate; i <= endDate; ){
if (i.getDay() == 0){
totalSundays++;
}
i.setTime(i.getTime() + 1000*60*60*24);
}
console.log(totalSundays);

// Find date of sundays b/w two dates
var fromDate = new Date('2022-10-26')
var toDate = new Date('2022-11-31')
var sunday = 0
var milisec = 1000 * 60 * 60 * 24;
while (fromDate <= toDate) {
var day = fromDate.getDay()
if (day == 0) {
sunday++
console.log('Date of sunday:', fromDate)
}
fromDate = new Date(+fromDate + milisec)
}
console.log('Total no. of sundays:', sunday)

Related

How to count number of days after excluding weekends using js

I have one query where I need to count number of business days from today to given number,
Like today is 09/14/2021 & given number is 10 I want the last date 09/28/2021 as it is 10th working day from today. I tried below to count day different
var startDate = new Date();
var endDate = new Date();
if(res.defaultLeadTime !== 0){
endDate.setDate(startDate.getDate() + 10);
}
I am getting 24th Sep, 2021. Now I am counting weekends between two dates
countWeekendDays = ( d0, d1 ) => {
var ndays = 1 + Math.round((d1.getTime()-d0.getTime())/(24*3600*1000));
var nsaturdays = Math.floor( (d0.getDay()+ndays) / 7 );
return 2*nsaturdays + (d0.getDay()==0) - (d1.getDay()==6);
}
And adding these number of days in the counting gives me another date but I am confuse if there is again weekend in the new date range then what can I do with that days.
So anyone can please guide me for this.
try this :
var startDate = "14-SEPT-2021";
startDate = new Date(startDate.replace(/-/g, "/"));
var endDate = "", noOfDaysToAdd = 10, count = 0;
while(count < noOfDaysToAdd){
endDate = new Date(startDate.setDate(startDate.getDate() + 1));
if(endDate.getDay() != 0 && endDate.getDay() != 6){
count++;
}
}
alert(endDate);//You can format this date as per your requirement
Another Solution
startDate = new Date("09/17/2021");
endDate = new Date("10/28/2021");
// Calculate days_difference = (endDate milliseconds - startDate milliseconds) / (1000 * 60 * 60 * 24) to get results in days
var days_difference = (endDate.getTime() - startDate.getTime()) / 86400000;
// Calculate number of weekends during the whole duration
var weekdends = Math.floor(days_difference/7) * 2 ;
// Adjust weekends depend on start days
(days_difference%7)+startDate.getDay() == 6 ? weekdends+=2 :
(days_difference%7)+startDate.getDay() == 5 ? weekdends+=1 :
weekdends;
// Calculate Working Days
var workDays = days_difference - weekdends
console.log("Working days",(workDays));

How to get the number of days with dates of a given week number by using JavaScript

I want to show them in a loop
Having an understanding of JavaScript & jQuery.
I have done to get the week number in a loop by using this code, for now, I want to get all days with dates of the given week number
function printWeekNumber() {
var dateFrom =
document.getElementById("txtFrom").value;
var dateF = new Date(dateFrom);
var resultFrom = dateF.getWeekNumber();
Date.prototype.getWeekNumber = function () {
var oneJan =
new Date(this.getFullYear(), 0, 1);
// calculating number of days
//in given year before given date
var numberOfDays =
Math.floor((this - oneJan) / (24 * 60 * 60 * 1000));
// adding 1 since this.getDay()
//returns value starting from 0
return Math.ceil((this.getDay() + 1 + numberOfDays) / 7);
}
function printWeekNumber() {
var dateFrom =
document.getElementById("txtFrom").value;
var dateF = new Date(dateFrom);
var resultFrom = dateF.getWeekNumber();
var dateTo =
document.getElementById("txtTo").value;
var dateT = new Date(dateTo);
var resultTo = dateT.getWeekNumber();
for (var i = resultFrom; i <= resultTo; i++) {
alert(i);
}
}
}
Please help me I am stuck in this step.

Calendar to show today's current date with the next 60 days

I have created a calendar that successfully displays todays current date. It also shows the remaining months however I am trying to change the functionality of the calendar so that it only shows the next 60 days from today's current date.
The code so far:
var todayDate = new Date();
var finalDate = new Date(todayDate)
finalDate.setDate(todayDate.getDate() + 60)
var dayNumber = todayDate.getDate();
var month = todayDate.getMonth();
var year = todayDate.getFullYear();
var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var calendarTable = document.getElementById("calendar-body");
document.getElementById("month").innerHTML = months[month];
document.getElementById("year").innerHTML = year;
function createCalendar(month, year) {
var firstDay = new Date(year, month).getDay();
var totalDays = daysInMonth(month, year);
blankDates(firstDay);
for (var day = 1; day <= totalDays; day++) {
var cell = document.createElement("li");
var cellText = document.createTextNode(day);
if (
dayNumber === day &&
month === todayDate.getMonth() &&
year === todayDate.getFullYear()
) {
cell.classList.add("todays-day");
}
cell.setAttribute("data-day", day);
cell.setAttribute("data-month", month);
cell.setAttribute("data-year", year);
cell.classList.add("singleDay");
cell.appendChild(cellText);
calendarTable.appendChild(cell);
}
}
function daysInMonth(month, year) {
return new Date(year, month + 1, 0).getDate();
}
function blankDates(count) {
for (var x = 0; x < count; x++) {
var cell = document.createElement("li");
var cellText = document.createTextNode("");
cell.appendChild(cellText);
calendarTable.appendChild(cell);
}
}
createCalendar(month, year);
Any ideas would be great. Thanks :)
First you need to find the number of dates between two dates,
In this case is finalDate and todayDate
var diff = Math.floor(( Date.parse(finalDate) - Date.parse(todayDate)) / 86400000);
You get the difference days (or NaN if one or both could not be parsed). The parse date gived the result in milliseconds and to get it by day you have to divided it by 24 * 60 * 60 * 1000
The output of the diff now is 60
Then you add the diff variable into the for loop.
Woking example
Just an idea.
But you could generate an array of the dates between now and 60 days.
Then loop through that array to build the calendar.
This way the Date functions can be used for each date in the array.
Here's a simple function to generate such array.
function getDateRange(pStartDate, pDays) {
let days = pDays || 1;
let dates = [];
let n = 0;
let startDate = new Date(pStartDate.toISOString().slice(0,10));
let endDate = new Date(startDate.getTime() + (days * 86400000));
do {
dates.push(new Date(startDate.getTime() + (n * 86400000)));
n++;
} while (n <= days);
let obj = {
startDate : startDate,
endDate : endDate,
days : dates.length,
dates : dates
}
return obj;
}
var dateRange = getDateRange(new Date(), 60);
console.log(dateRange.dates);

get last 7 days when user picks up a date

I have a datetimepicker where the user picks up a date, and my requirement is I need 7 days difference between his selected date.
For eg,
if user has selected 2017-03-01 so i need last 7 days from 2017-03-01 and NOT the current date
All answers i checked here were based on days difference from today.
Can anyone help me out here ?
$("#dateTimePickerIdWhereUserSelectsHisDate").val() - (7 * 24 * 60 * 60 * 1000);
this was on one of the answers but didn't work.
How can I achieve this ?
Try This
SelectDateTime will give you selected date
604800000 is 7 days in miliseconds
prevDate will give you last 7 days Date
$("#startDate").on("dp.change", function(e) {
if (e.oldDate != null) {
if (e.date.format('D') != e.oldDate.format('D')) {
var selectDateTime = e.date["_d"].getTime();
var prevDateTImeMili = selectDateTime - 604800000;
var prevDate = msToDateTime(prevDateTImeMili)
$('#startDate').data("DateTimePicker").hide();
}
}
});
msToDateTime is a function which converts milliseconds to DateTime
function msToDateTime(s) {
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
if(s != null){
s = new Date(s);
// var d = new Date(s);
// var d = new Date(s.getTime()+s.getTimezoneOffset()*60*1000+timeConversionToMilliseconds(sessionStorage.getItem("accounttimezone").split('+')[1]+':00'))
var d = new Date(s.getTime()+(s.getTimezoneOffset()*60*1000)+ (330 *60*1000));
dformat = [ d.getFullYear(),
(d.getMonth()+1).padLeft(),
d.getDate().padLeft()].join('-')+
' ' +
[ d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
return dformat;
}else{
return " ";
}
}
function getNDaysBefore(dateString, numberOfDaysBefore) {
let startingDate = new Date(dateString).getTime();
let datesArray = [],
daysCounter = 0,
day = 1000 * 60 * 60 * 24;
while (daysCounter < numberOfDaysBefore + 1) {
let newDateBeforeStaring = startingDate - day * daysCounter;
datesArray.push(new Date(newDateBeforeStaring));
daysCounter++;
}
return datesArray;
}
var dateString = "2016-03-01";
alert(getNDaysBefore(dateString,7));
With that kind of a function you can get any N days before the given date as an array of Date objects

how to get difference in year where dates are in yyyy-mm-dd?

i want to get the difference between two dates which are give in yyyy-mm-dd format difference should be in year.
var ds='2002-09-23';
var today_date = new Date();
alert(today_date);
Date.prototype.yyyymmdd = function() {
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
var dt = yyyy +"-"+(mm[1]?mm:"0"+mm[0]) +"-"+ (dd[1]?dd:"0"+dd[0]);// padding
var num_years = diff_date/31536000000;
alert(num_years);
if (num_years>18){
alert (num_years);
}else{
alert ("i m not 18");
}
please help me out.
This is much shorter:
var yearsApart = new Date(new Date - new Date('2002-09-23')).getFullYear()-1970
… but be careful to take care of non UTC time zones by providing the correct datetime string!
You need no library for this, just pure javascript:
function wholeYearsBetweenTwoDates(dateOneString, dateTwoString) {
// assuming that dateTwo is later in time than dateOne
var dateOne = getDateFromString(dateOneString);
var dateTwo = getDateFromString(dateTwoString);
var result = dateTwo.getFullYear() - dateOne.getFullYear();
dateOne.setFullYear(dateTwo.getFullYear());
if (dateOne > dateTwo) {
// compensate for the case when last year is not full - e.g., when
// provided with '2009-10-10' and '2010-10-09', this will return 0
result -= 1;
}
return result;
}
function getDateFromString(stringDate) {
var dateParts = stringDate.split('-');
var result = new Date(dateParts[0], dateParts[1], dateParts[2]);
return result;
}
Try the following code to get the difference in years...
function getDateDiffInYears(date1, date2) {
var dateParts1 = date1.split('-')
, dateParts2 = date2.split('-')
, d1 = new Date(dateParts1[0], dateParts1[1]-1, dateParts1[2])
, d2 = new Date(dateParts2[0], dateParts2[1]-1, dateParts2[2])
return new Date(d2 - d1).getYear() - new Date(0).getYear() + 1;
}
var diff = getDateDiffInYears('2005-09-23', '2012-07-3');
console.log(diff); // => 7 years
Good luck!
I had been using the formula var yearsApart=milli/milliPerYear but when the day and the month are the same the rounded value is not correct.
Here you have the script I'm using right now ...
function yearDifferenceDates(firstDateDay, firstDateMonth, firstDateYear, secondDateDay, secondDateMonth, secondDateYear) {
var fisrtDate = new Date(firstDateYear, firstDateMonth - 1, firstDateDay);
var secondDate = new Date(secondDateYear, secondDateMonth - 1, secondDateDay);
if(firstDateDay == secondDateDay && (firstDateMonth - 1) == (secondDateMonth - 1)) {
return Math.round((secondDate-fisrtDate)/(1000*60*60*24*365.242199));
}
return Math.floor((secondDate-fisrtDate)/(1000*60*60*24*365.242199));
}
First you have to pick a JavaScript library for parsing dates using a format string (so you can provide date in the format you prefer). Try this great library (at least you do not have to care about implementation details. Date constructor and Date.parse methods must match but it's not mandatory they can parse a simple date in that format).
var date1 = getDateFromFormat("1999-10-10", "YYYY-MM-DD");
var date2 = getDateFromFormat("2012-10-10", "YYYY-MM-DD");
Then, when you have to calculate the difference:
var millisecondsPerSecond = 1000;
var millisecondsPerMinute = millisecondsPerSecond * 60;
var millisecondsPerHour = millisecondsPerMinute * 60;
var millisecondsPerDay = millisecondsPerHour * 24;
var millisecondsPerYear = millisecondsPerDay * 365.26;
var years = Math.round((date2 - date1) / millisecondsPerYear);
If you need a raw calculation you can use getFullYear() directly.
You can compare dates more easily if you convert them to their millisecond values.
var birthday = new Date('2002-09-23');
var now = new Date();
var age = now.getTime() - birthday.getTime();
if (age < (1000 * 60 * 60 * 24 * 365 * 18)) { // number of milliseconds in 18 years
document.write('not over 18');
} else {
document.write('over 18');
}
Above has a little bug but this work :)
NOT WORKING: var millisecondsPerHour = millisecondsPerMinute = 60;
WORKING FINE: var millisecondsPerHour = millisecondsPerMinute * 60;
But thx Adriano Repetti
Here the complete code (with dot Format)
var date1 = "01.01.2014";
var date2 = "31.12.2016";
var date1 = date1.split(".");
var date2 = date2.split(".");
date1 = String(date1[2] +"-"+ date1[1] +"-"+ date1[0]);
date2 = String(date2[2] +"-"+ date2[1] +"-"+ date2[0]);
var date1 = Date.parse(date1);
var date2 = Date.parse(date2);
//(Not for Europa :) )
//var date1 = Date.parse("2014-01-01");
//var date2 = Date.parse("2016-12-31");
var millisecondsPerSecond = 1000;
var millisecondsPerMinute = millisecondsPerSecond * 60;
var millisecondsPerHour = millisecondsPerMinute * 60;
var millisecondsPerDay = millisecondsPerHour * 24;
var millisecondsPerYear = millisecondsPerDay * 365.26;
// IN YEARS
var years = (date2 - date1) / millisecondsPerYear;
// IN MONTHS
var month = years * 12 // Very tricky, I know ;)
var d1=new Date(2002, 9, 23);
var d2=new Date();
var milli=d2-d1;
var milliPerYear=1000*60*60*24*365.26;
var yearsApart=milli/milliPerYear;
console.log(yearsApart)

Categories