Calculate days of the week from Monday to Saturday - javascript

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
*/

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);
}

how can get particular day of date when you have start and end date

I have a start date 4/10/2021 and end date 4/12/2021
I want get Tuesday, Thursday and Friday date in jquery
I found this solution:
var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);
//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var j = 1;
var count = 0;
//getting the all fridays in a financial year
for ( var i = 0; x<y; i += j) {
if (x.getDay() == 5) {
$("#append_text").append("Date : " + x.getDate() + "/"
+ (x.getMonth() + 1) + "<br>");
x = new Date(x.getTime() + (7 * 24 * 60 * 60 * 1000));
j = 7;
count++;
} else {
j = 1;
x = new Date(x.getTime() + (24 * 60 * 60 * 1000));
}
}
$("#append_text").append("total fridays : " + count + "<br>");
but it return only Friday and i think it doesn't work truly
The result is:
Date : 5/11
Date : 12/11
Date : 19/11
Date : 26/11
Date : 3/12
Date : 10/12
Date : 17/12
Date : 24/12
Date : 31/12
total fridays : 9
The solution link is here:
Get Friday Dates of Year in javascript using jquery
do you have any solution for that?
As mentioned in getDay() docs:
The getDay() method returns the day of the week for the specified date according to local time, where 0 represents Sunday.
So, clearly
if (x.getDay() == 5)
5 here stands for Friday. So, if you also need Tuesday as 2 & Thursday as 4, you simply need to modify for loop like:
var day = x.getDay();
if (day === 2 || day === 4 || day === 5)
Demo:
var x = new Date();
//set the financial year starting date
x.setFullYear(2021, 10, 04);
//set the next financial year starting date
var y = new Date();
y.setFullYear(2021, 12, 04);
var html = '';
var count = 0;
//getting the all fridays in a financial year
for (var i = 0; x < y; i++) {
var day = x.getDay();
if (day === 2 || day === 4 || day === 5) {
html += "Date : " + x.getDate() + "/" + (x.getMonth() + 1) + "<br>";
if (day === 5)count++;
}
x.setDate(x.getDate() + 1)
}
$("#append_text").append(html);
$("#append_text").append("total fridays : " + count + "<br>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id=append_text></div>
Try this.
var start = new Date(2021, 10, 04);
var end = new Date(2021, 12, 04);
var tuesdays = [], thursdays = [], fridays = [];
for (var current = start; current <= end; current.setDate(current.getDate() + 1)) {
var day = current.getDay();
switch (day) {
case 2: // tuesdays
tuesdays.push(formatDate(current));
break;
case 4: // thursdays
thursdays.push(formatDate(current));
break;
case 6: // fridays
fridays.push(formatDate(current));
break;
default: //other dates
break;
}
}
function formatDate(d) { // formats date to dd/mm/yyy
return d.getDate() + '/' + (d.getMonth() + 1) + '/' + d.getFullYear();
}
console.log(tuesdays.length + " Tuesdays: ", tuesdays.join('\t'));
console.log(thursdays.length + " Thursdays: ", thursdays.join('\t'));
console.log(fridays.length + " Fridays: ", fridays.join('\t'));
You can do this by iterating over every date between the two dates and saving the ones that fit some criterion, or you can get the first of the required dates, then add 7 days to get each weekly until the end date, e.g.
// Parse date in day/month/year format
function parseDMY(s) {
let [d, m, y] = s.split(/\D/);
return new Date(y, m-1, d);
}
// Get next day by dayNumber on or after date, default today
function getDayOfWeek(day, date) {
let d = date? new Date(+date) : new Date();
d.setDate(d.getDate() - d.getDay() + day +
(day < d.getDay()? 7 : 0));
return d;
}
// Format date as dd/mm/yyyy
function formatDMY(date) {
return date.toLocaleString('en-GB', {
year : 'numeric', // remove if year not required
month: '2-digit',
day : '2-digit'
});
}
// Given start and end date, get days by day number between
// dates inclusive
function getDaysBetweenDates(d0, d1, ...days){
let dStart = parseDMY(d0);
let dEnd = parseDMY(d1);
// Guard against endless loop
if (dEnd < dStart) return;
let dates = [];
while (dStart <= dEnd) {
days.forEach(day => {
let d = getDayOfWeek(day, dStart);
if (d <= dEnd) dates.push(formatDMY(d));
});
dStart.setDate(dStart.getDate() + 7);
}
return dates.sort(
(a, b) => a.split(/\D/).reverse().join('').localeCompare(
b.split(/\D/).reverse().join(''))
);
}
// Get all Tue, Thu and Fri between 4 Oct 2021 and 4 Dec 2021 inclusive
console.log(getDaysBetweenDates('4/10/2021', '4/12/2021', 2, 4, 5));
I've left the year in the date, it's easily removed by removing year: 'numeric', from the formatting options.
Note that in the OP:
y.setFullYear(2021, 12, 04);
creates a Date for 4 Jan, 2022 not 4 Dec 2021 because months are zero indexed, so December is 11. A month value of 12 rolls over to January of the following year.

Calculating weekends within a month

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) + '.');

Adding months to current date and if its saturday adding 2 days to input?

I need to add months so I use date.getMonth() +8; and its a Saturday but I need to eliminate weekends. If I add these lines of code:
if(date.getDay() % 6)
var date.getdate()+1;
It doesn't work. So what can i do?
Here to fiddle https://jsfiddle.net/a3f3yb0s/
and here to snippet
var date = new Date();
var day = date.getDate();
var month = date.getMonth() +8;
var year = date.getFullYear();
var year2 = date.getFullYear() +1;
if(month>12) {
month=month%12;
year=year2;
}
if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;
var today = year + "-" + month + "-" + day;
document.getElementById('theDate').value = today;
<input type="date" id="theDate">
Why not just do the calculations on the date object and let the browser handle all the calendar calculations:
// get a date object
// 8 months from 2016-01-01 is a Saturday
var date = new Date(2016, 1, 1);
// add 8 months
date.setMonth(date.getMonth() + 8);
alert(date); // will show a Saturday
// check if it is a saturday
if(date.getDay() == 6)
{
// if it is then add two days
date.setDate(date.getDate() + 2);
}
alert(date); // will show a Monday

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));
}

Categories

Resources