Calculating weekends within a month - javascript

I want to build a simple function that would receive a particular month to check. In return it would provide the amount of weekend days it counted within that month.
In the code I'm assuming that the current year is the relevant year to simplify the task.
The problem is it's not return the proper answer for weekends in reality when going over a calendar and counting it manually.
workDays(4); // submitting the month to check for
function workDays(monthCheck) //Calculate the actual work days: eliminate weekends from month
{
// init month to check as proper date variable and setting days to 0 for total days
var month = new Date(new Date().getFullYear(), monthCheck+1, 0);
var daysOff = 0; //init
for(i = month.getDate(); i>=0; i--) //check for days that = 0 or 6 (Sunday OR Saturday)
{
if(new Date(month.getFullYear(), monthCheck, i).getDay() == 0 || new Date(month.getFullYear(), monthCheck, i).getDay() == 6)
{
console.log(daysOff++); // weekend day added to weekend days counter
}
}
return console.log("The days off for the month of " + (month.getMonth()) + " are " + daysOff + " days off.");
}

I find your logic very confusing. I refactored the code to an (imo) more readable version, and the result seems as expected:
nonWorkDays(4);
function nonWorkDays(month)
{
var current = new Date(new Date().getFullYear(), month - 1, 1);
var daysOff = 0; //init
// as long as our date is in the requested month
while (current.getMonth() == month -1) {
// saturday or sunday?
if (current.getDay() == 0 || current.getDay() == 6) {
daysOff++;
console.log(daysOff, current);
}
// move to next day
current.setDate(current.getDate() + 1);
}
console.log("The days off for the month of " + month + " are " + daysOff + " days off.");
return daysOff;
}
And a fiddle to demonstrate: https://jsfiddle.net/4kmtemfy/

Not sure where you went wrong but this seems right:
var d = new Date();
var getTot = daysInMonth(d.getMonth(),d.getFullYear());
var weekends = new Array();
for(var i=1;i<=getTot;i++){
var newDate = new Date(d.getFullYear(),d.getMonth(),i)
if(newDate.getDay()==0 || newDate.getDay()==6){
weekends.push(i)
}
}
console.log(weekends.length);
function daysInMonth(month,year) {
return new Date(year, month, 0).getDate();
}

Your issue is with monthCheck+1. Since months are zero indexed and you want the month number of the following month, don't subtract 1. You can also simplify the logic somewhat:
function workDays(monthCheck) {
// Create date for last day of month to check
var month = new Date(new Date().getFullYear(), monthCheck, 0);
var daysOff = 0;
// For each day of the month
for(var i = month.getDate(); i>=0; i--) {
// Add day off for Saturday and Sunday
if (!(month.getDay()%6)) {
daysOff++;
}
month.setDate(month.getDate()-1);
}
return daysOff;
}
var month = 4;
console.log('Days off for ' + month + ' are ' + workDays(month) + '.');

Related

JavaScript or Jquery - How to display last week of the month and next month's first Monday

How do you display only when it's the last week of the month (the text below).
The DATE that will be displayed here is next month's first Monday.
"Due on DD/MM/YY"
To detect if this is the last week in month you can follow this example:
https://www.javatpoint.com/calculate-current-week-number-in-javascript
To get next monday, you can call this function:
getNextMonday(){
var date = new Date();
date.setDate(date.getDate() + (1 + 7 - date.getDay()) % 7);
return date;
}
You can use the below JS Code. It will show the alert on last week of month means from last monday of month.
function Get_Last_Monday_of_Month()
{
var year = new Date().getFullYear();
var month = new Date().getMonth() + 1;
var dat = new Date(year+'/'+month+'/1');
var currentmonth = month;
var firstmonday = false;
while (currentmonth === month)
{
firstmonday = dat.getDay() === 1 || firstmonday;
dat.setDate(dat.getDate()+(firstmonday ? 7 : 1));
currentmonth = dat.getMonth()+1;
}
dat.setDate(dat.getDate()-7);
return dat;
}
function Get_Next_Coming_Monday()
{
var date = new Date();
date.setDate(date.getDate() + (1 + 7 - date.getDay()) % 7);
return date;
}
var d1 = new Date();
var d2 = Get_Last_Monday_of_Month();
var d3 = Get_Next_Coming_Monday();
if (d1.getTime() >= d2.getTime())
{
var datestring = ("0" + d3.getDate()).slice(-2) + "/" + ("0"+(d3.getMonth()+1)).slice(-2) + "/" + d3.getFullYear();
document.write ("Due on " + datestring);
}

JavaScript application for showing the weekend dates?

I thought a lot - I tried but I could not solve it. I need a JavaScript application that shows the nearest weekend dates in the current date.
If it's a weekend now, give it the dates of this weekend, if not, then next weekend's dates.
I'm waiting for your help.
Respects.
You can use the built-in Date constructor.
var date = new Date();
var day = date.getDay();
var saturday;
var sunday;
if(day === 0 || day === 6){ //0 for Sunday, 6 for Saturday
saturday = date;
sunday = new Date(saturday.getTime());
sunday.setDate(saturday.getDate() + (day === 0 ? -1 : 1));
if(day === 0){
var temp = saturday;
saturday = sunday; //Confusing, but they are actually the wrong dates, so we are switching the dates
sunday = temp;
temp = null; //Free up some memory!
}
}
else{
//This is the complicated part, we need to find when is the next Saturday
saturday = new Date(date.getFullYear(), date.getMonth(), (date.getDate() + 6) - day);
sunday = new Date(saturday.getTime());
sunday.setDate(saturday.getDate() + (saturday.getDay() === 0 ? -1 : 1));
}
date = day = null; //Free up some memory!
document.body.innerText = [saturday, sunday];
To get the date, use saturday.getDate() or sunday.getDate().Remember that Date months are 0-based. See here for more info.
var chosenDay = new Date();
var box = [];
var counting = 0;
for (var i = 0; i < 7; i++) {
chosenDay.setDate(chosenDay.getDate() + counting);
var day = chosenDay.getDate();
var dayy = chosenDay.getDay();
var month = chosenDay.getMonth()+1;
var year = chosenDay.getFullYear();
box.push({day: day, dayy: dayy});
counting = 1;
};
Now to find Saturday and Sunday
box.map(function(obj) {
if (obj.dayy === 6) {
console.log('Saturday found');
alert(obj.day);
};
if (obj.dayy === 0) {
console.log('Sunday found');
alert(obj.day);
};
});
I interpret the "nearest" weekend as being the previous weekend for Monday and Tuesday, and the next weekend for Thursday and Friday. You didn't provide any information on what to do with Wednesday.
However, from other answers it seems you want either the current weekend for Saturday and Sunday and or the next weekend for weekdays.
The following is a little more concise than other answers:
/* Get nearest weekend to the provided date
** #param {Date} date - date to get weekends nearst to
** #returns {Array} array of Dates [Saturday, Sunday]
*/
function getNearestWeekend(date) {
// Copy date so don't mess with provided date
var d = new Date(+date);
// If weekday, move d to next Saturday else to current weekend Saturday
if (d.getDay() % 6) {
d.setDate(d.getDate() + 6 - d.getDay());
} else {
d.setDate(d.getDate() - (d.getDay()? 0 : 1));
}
// Return array with Dates for Saturday, Sunday
return [new Date(d), new Date(d.setDate(d.getDate() + 1))]
}
// Some tests
[new Date(2017,0,7), // Sat 7 Jan
new Date(2017,0,8), // Sun 8 Jan
new Date(2017,0,9), // Mon 9 Jan
new Date(2017,0,12) // Thu 12 Jan
].forEach(function(d) {
var opts = {weekday:'short', day:'numeric', month:'short'};
console.log('Date: ' + d.toLocaleString('en-GB',opts) + ' | Next weekend: ' +
getNearestWeekend(d).map(d =>d.toLocaleString('en-GB',opts)).join(' and ')
);
});

How to get first week number of the month - javascript

I am populating all the months in Dropdown list, and i am enabling up to current month and remain months will be disabled, like
var date = new Date();
var month = new Date().getMonth() + 1;
var weeknum=//getting week number of the month
var options = $('#ddlMonth option');
var values = $.map(options, function (option) {
return option.value;
});
for (var i = 0; i <= values.length; i++) {
if (i > month) {
$("#ddlMonth option[value=" + i + "]").attr('disabled', true);
}
}
$('#ddlMonth').val(month);
Now I want to disable month if current week of the current month is first week.
Date.prototype.getMonthWeek = function(){
var firstDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();
return Math.ceil((this.getDate() + firstDay)/7);
}
Demo
http://jsfiddle.net/ay10bmpm/
 
Ref
http://www.somethinghitme.com/2010/04/14/how-to-get-the-week-in-a-month-for-a-date-with-javascript/
function(){
var d = new Date();
d.setHours(0,0,0);
d.setDate(d.getDate()+4-(d.getDay()||7));
return Math.ceil((((d-new Date(d.getFullYear(),0,1))/8.64e7)+1)/7);
};
This will get you the week in year and from this is simple math. (maybe not so simple for 5 weeks per month).
Or you can get the number of the week function from this fiddle : http://jsfiddle.net/OlsonDev/5mXF6/1/ (works with 5 weeks, tested)

javascript date of specific day of the week in MM/dd/yyyy format not libraries

I know there are a lot of threads about finding the date of a specific day of the week in javascript but the all give it in the format like so:
Sun Dec 22 2013 16:39:49 GMT-0500 (EST)
but I would like it in this format 12/22/2013 -- MM/dd/yyyy
Also I want the most recent Sunday and the code I have been using does not work all the time. I think during the start of a new month it screws up.
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:0); // adjust when day is sunday
return new Date(d.setDate(diff));
}
I have code that gives me the correct format but that is of the current date:
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
this prints:
>>> 12/23/2013
when I try to subtract numbers from the day it does not work, so I cannot get the dat of the most recent Sunday as MM/dd/yyyy
How do I get the date of the most recent sunday in MM/dd/yyyy to print, without using special libraries?
You can get the current weekday with .getDay, which returns a number between 0 (Sunday) and 6 (Saturday). So all you have to do is subtract that number from the date:
currentTime.setDate(currentTime.getDate() - currentTime.getDay());
Complete example:
var currentTime = new Date()
currentTime.setDate(currentTime.getDate() - currentTime.getDay());
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
console.log(month + "/" + day + "/" + year)
// 12/22/2013
To set the date to any other previous weekday, you have to compute the number of days to subtract explicitly:
function setToPreviousWeekday(date, weekday) {
var current_weekday = date.getDay();
// >= always gives you the previous day of the week
// > gives you the previous day of the week unless the current is that day
if (current_weekday >= weekday) {
current_weekday += 6;
}
date.setDate(date.getDate() - (current_weekday - weekday));
}
To get the date of next Sunday you have to compute the number of days to the next Sunday, which is 7 - currentTime.getDay(). So the code becomes:
currentTime.setDate(currentTime.getDate() + (7 - currentTime.getDay()));
Subtract days like this
// calculate days to subtract as per your need
var dateOffset = (24*60*60*1000) * 5; //5 days
var date = new Date();
date.setTime(date.getTime() - dateOffset);
var day = date.getDate() // prints 19
var month = date.getMonth() + 1
var year = date.getFullYear()
document.write(month + '/' + day + '/' + year);
Here is my suggestion. Create a function like so... in order to format any date you send it.
function formatDate(myDate) {
var tmp = myDate;
var month = tmp.getMonth() + 1;
var day = tmp.getDate();
var year = tmp.getFullYear();
return (month + "/" + day + "/" + year);
}
Now, to print the current date, you can use this code here:
var today = new Date();
var todayFormatted = formatDate(today);
To get the previous Sunday, you can use a while loop to subtract a day until you hit a Sunday, like this...
var prevSunday = today;
while (prevSunday.getDay() !== 0) {
prevSunday.setDate(prevSunday.getDate()-1);
}
var sundayFormatted = formatDate(prevSunday);
To see the whole thing together, take a look at this DEMO I've created...
** Note: Make sure you turn on the Console tab when viewing the demo. This way you can see the output.
You can create prototype functions on Date to do what you want:
Date.prototype.addDays = function (days) {
var d = new Date(this.valueOf());
d.setDate(d.getDate() + days);
return d;
}
Date.prototype.getMostRecentPastSunday = function () {
var d = new Date(this.valueOf());
return d.addDays(-d.getDay()); //Sunday is zero
}
Date.prototype.formatDate = function () {
var d = new Date(this.valueOf());
//format as you see fit
//http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
//using your approach...
var month = d.getMonth() + 1
var day = d.getDate()
var year = d.getFullYear()
return month + "/" + day + "/" + year;
}
console.log((new Date()).getMostRecentPastSunday().formatDate());
console.log((new Date("1/3/2014")).getMostRecentPastSunday().formatDate());
//or...
var d = new Date(); //whatever date you want...
console.log(d.getMostRecentPastSunday().formatDate());
Something like this will work. This creates a reusable dateHelper object (you will presumably be adding date helper methods since you don't want to use a library off the shelf). Takes in a date, validates that it is a date object, then calculates the previous Sunday by subtracting the number of millis between now and the previous Sunday.
The logging at the bottom shows you how this works for 100 days into the future.
var dateHelper = {
getPreviousSunday: function (date) {
var millisInADay = 86400000;
if (!date.getDate()) {
console.log("not a date: " + date);
return null;
}
date.setMilliseconds(date.getMilliseconds() - date.getDay() * millisInADay);
return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear();
}
}
var newDate = new Date();
console.log(dateHelper.getPreviousSunday(newDate));
var now = newDate.getTime();
for (var i=1; i<100; i++) {
var nextDate = new Date(now + i * 86400000);
console.log("Date: + " nextDate + " - previous sunday: " + dateHelper.getPreviousSunday(nextDate));
}

Calculate days of the week from Monday to Saturday

In my form I have a datafield where I select the day of the week!
For example if I select today 23-03-2012 Friday, I need to get an array of days from previous Monday to this next Saturday.
array:
[0],[19-03-2012],[Monday]
[1],[20-03-2012],[Monday]
[2],[21-03-2012],[Wednesday]
[3],[22-03-2012],[Monday]
[4],[23-03-2012],[Friday]
[5],[24-03-2012],[Saturday]
How can i do it for any selected day of the week obviously paying attention to changes?
Thanks
This function will return an array of all the dates in the week of date, Monday to Saturday.
function GetDaysOfWeek(date)
{
var days = new Array();
for (var i = 0; i < 6; i++)
{
days[i] = new Date(date.getYear(),
date.getMonth(),
date.getDate() - date.getDay() + 1 + i);
}
return days;
}
mayby try out MomentJs: http://momentjs.com/docs/
some examples:
moment().day(-7); // set to last Sunday (0 - 7)
moment().day(7); // set to next Sunday (0 + 7)
moment().day(10); // set to next Wednesday (3 + 7)
moment().day(24); // set to 3 Wednesdays from now (3 + 7 + 7 + 7)
For display the current day of the week:
var now = new Date();
var dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.write("Today is " + dayNames[now.getDay()] + ".");
First find todays date
Find the last monday (including today)
Show that date, and the next 5 days after it (Tuesday-Saturday)
var d = new Date();
if (d.getDay()==0){
d.setDate(d.getDate() + 1);
}
​while (d.getDay() != 1){
d.setDate(d.getDate() - 1);
}
var days = new Array();
for (var i = 0; i < 6; i++){
days[i] = d.getDate() + i;
}
return days;
try this :
var dayString = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var now = new Date();
var currentDay = now.getDay(); // return 0 for Sunday, 6 for Saturday
var result = [];
var tempDate = new Date(now.getTime());
tempDate.setDate(now.getDate()-(currentDay+6)%7); // now tempDate is previous Monday
while(tempDate.getDay()!=0) {
var currentMonth = tempDate.getMonth()+1;
if(currentMonth<10) currentMonth = "0"+currentMonth;
result.push([tempDate.getDay()-1,tempDate.getDate()+"-"+currentMonth+"-"+tempDate.getFullYear(),dayString[tempDate.getDay()]]);
tempDate.setDate(tempDate.getDate()+1);
}
console.log(result);
Something like the following will do the trick, I"m sure you can get the formatting to where you want it.
// Assuming d is a date object
function getDateArray(din) {
// Add leading zero to one digit numbers
function aZ(n){return (n<10? '0':'') + n;}
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
var d = new Date(din); // Don't wreck input date
var dn = d.getDay();
var a = [];
var i = 6; // length of day array
if (!dn) {
// It's Sunday, what now?
return ['Sunday!'];
}
d.setDate(d.getDate() + 6 - dn); // Next Saturday
do {
a[i--] = i + ' ' + aZ(d.getDate()) +
'-' + aZ(d.getMonth() + 1) +
'-' + d.getFullYear() +
' ' + days[d.getDay()];
d.setDate(d.getDate() - 1);
} while (i);
return a;
}
// Test it
var date = new Date(2012,2,2)
alert( date + '\n\n' + getDateArray(date).join('\n'));
/*
Fri Mar 02 2012 00:00:00
0 27-02-2012 Monday
1 28-02-2012 Tuesday
2 29-02-2012 Wednesday
3 01-03-2012 Thursday
4 02-03-2012 Friday
5 03-03-2012 Saturday
*/

Categories

Resources