I'm facing issue with excluding weekend dates in JavaScript.For my business requirement I want to exclude 3 days from date object Friday, Saturday and Sunday in every week.What I need here is the values of Friday should display as Monday, Saturday as Tuesday and Sunday as Wednesday. I'm able to do this.
The issue that I'm facing here is when we run the above example the a[0] value should be 21-SEP-2017 but I'm getting 20-SEP-2017 and remaining array values should not change. So please do help me out in resolving this issue
var a = ["21-SEP-2017", "22-SEP-2017", "23-SEP-2017", "24-SEP-2017", "25-SEP-2017"];
for (i = 0; i < a.length; i++) {
var startDate = a[i];
startDate = new Date(startDate.replace(/-/g, "/"));
var endDate = "",
noOfDaysToAdd = 1;
var count = 0;
endDate = new Date(startDate.setDate(startDate.getDate()));
if (startDate.getDay() != 0 && startDate.getDay() != 5 && startDate.getDay() != 6) {
endDate = new Date(startDate.setDate(startDate.getDate() + i - 1));
} else {
startDate.setDate(startDate.getDate() + 3)
endDate = new Date(startDate.setDate(startDate.getDate()));
}
console.log(endDate); //You can format this date as per your requirement
}
Your code seems not finished: the variables noOfDaysToAdd and count are never used, and if they were, they would be reset in every iteration of the loop, which cannot be the purpose.
That your output shows 20 September is because you did not output a stringified version of the date, but the date object itself, and then console.log will display the date as a UTC date (notice the time part matches the timezone difference). Instead use .toString() or another way to turn the date to a localised string.
Here is how you could do it:
function toDate(s) {
return new Date(s.replace(/-/g, '/'));
}
function toStr(dt) {
var months = ["JAN","FEB","MAR","APR","MAY","JUN",
"JUL","AUG","SEP","OCT","NOV","DEC"];
return [('0'+dt.getDate()).substr(-2), months[dt.getMonth()], dt.getFullYear()]
.join('-');
}
var a = ["21-SEP-2017", "22-SEP-2017", "23-SEP-2017", "24-SEP-2017", "25-SEP-2017"],
add = 0;
var result = a.map(toDate).map(dt => {
dt.setDate(dt.getDate()+add);
var move = [0, 6, 5].indexOf(dt.getDay()) + 1;
if (move) {
add += move;
dt.setDate(dt.getDate()+move);
}
return dt;
}).map(toStr);
console.log(result);
Related
I have the weekday value (0-6 for Sun-Sat)...how do I get an array of days (starting on Sunday for the given week?
Here is what I'm trying to do:
A user clicks a day (ie: May 10) and it generates an array of the dates for the current week:
function selectWeek(date) {
selectedWeek = [];
let d = new Date(date.key);
console.log(d);
console.log(date.weekday, 'weekday');
console.log(date);
for (let i = 0; i < date.weekday; i++) {
console.log(i, 'pre');
let currD = d.setDate(d.getDate() - i).toString();
console.log(currD);
selectedWeek.push(currD);
}
for (let i = date.weekday; i < 7; i++) {
console.log(i, 'post');
selectedWeek.push(d.setDate(d.getDate() + i).toString());
}
console.log(selectedWeek);
}
I need Sunday through Saturday date objects.
I am not using a date library so prefer vanilla javascript solutions.
Create an array with 7 elements, subtract the weekday and add the index as day:
function selectWeek(date) {
return Array(7).fill(new Date(date)).map((el, idx) =>
new Date(el.setDate(el.getDate() - el.getDay() + idx)))
}
const date = new Date();
console.log(selectWeek(date));
I'm using
fill(new Date(date))
to create a copy and not modify the argument.
You can get the days of a month with the same concept:
function selectMonth(date) {
return Array(31).fill(new Date(date)).map((el, idx) =>
new Date(el.setDate(1 + idx))).filter(el => el.getMonth() === date.getMonth());
}
const date = new Date();
console.log(selectMonth(date));
here's how I would solve this one:
function selectWeek(date) {
let selectWeek = [];
for (let i=0; i<7; i++) {
let weekday = new Date(date) // clone the selected date, so we don't mutate it accidentally.
let selectedWeekdayIndex = date.getDay() // i.e. 5 for friday
let selectedDay = date.getDate() // 1-31, depending on the date
weekday.setDate(selectedDay - selectedWeekdayIndex + i)
selectWeek = [...selectWeek, weekday]
}
return selectWeek;
}
Let's take today's date as an example: 18.02.22. Friday.
We do 6 iterations. On first one we get the selectedWeekdayIndex, which is 5 for friday. We clone the date and re-set it's day (18) reducing it by this number: 18-5 = 13. This is the day for Sunday. Then we go on incrementing days by one to fill the rest of the week.
Of course it can be optimised and written much shorter, but I tried to show and explain the logic.
The .getDay() gives you the day of the week.
function selectWeek(date) {
const selectWeek = [];
let temp = date;
while (temp.getDay() > 0) temp.setDate(temp.getDate() - 1); // find Sunday
// get the rest of the week in the only do while loop ever created
do {
selectWeek.push(new Date(temp));
temp.setDate(temp.getDate() + 1);
} while (temp.getDay() !== 0);
return selectWeek;
/* for display purposes only */
// const dates = selectWeek.map((date) => date.toString());
// console.log(dates);
}
selectWeek(new Date());
selectWeek(new Date("2020-01-01"));
selectWeek(new Date("december 25, 1990"));
Did you check Date prototypes before?
I think Date.prototype.getDay() can do what you want:
function selectWeekDays(date) {
var i,
d = new Date(date),
a = [];
// console.log(d.getDay()); // Number of the day
d.setDate(d.getDate() - d.getDay() - 1); // Set date one day before first day of week
for (i=0; i<7; i++) {
d.setDate(d.getDate() + 1); // Add one day
a.push(d.valueOf());
}
return a;
}
var result = selectWeekDays('2022-01-01') // Satureday = 6
console.log(result);
result.forEach(e => console.log(new Date(e).toString()));
Image of my array valuesI have a function to "Wed 12/8" and "Wed 12/8". However, when I use them in this function they are not equal for some reason yet they are identical. The function does not append and acts as if they are completely different.
function filterDate() {
for (var i = 0; i < dateList.length; i++) {
if(dateList[i] == today) {
appendItem(filteredDate, dateList[i]);
appendItem(filteredID, stateID[i]);
appendItem(filteredCase, totalCases[i]);
appendItem(filteredState, usState[i]);
}
}
}
Here the get date code.
//Date
var now = new Date();
//Gets the current days date
var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var months = ['1','2','3','4','5','6','7','8','9','10','11','12'];
var weekday = days[now.getDay() - 1];
var day = now.getDate() - 1;
var month = months[now.getMonth()];
var today = weekday + " " + month + "/" + day;
//Console logs todays date
console.log(today);
The values are the exact same but the computer thinks they are not. When I manually change today to "Wed 12/8" it works but the variable seems to mess it up though I may be wrong. What's happening and how do I fix this as it is crucial to my program?
The problem should be the way you populate the dateList array. Are you sure it gets filled with strings too, and not for example date objects? The code you provided does not show anything related to that array.
Edit:
Based on the image you provided later, I think the issue will be that your strings in the array contain quotation marks.
Remove them from the strings. (For example by slicing the first and last characters from it in the filterDate function)
function filterDate() {
for (var i = 0; i < dateList.length; i++) {
if(dateList[i].slice(1,-1) == today) {
appendItem(filteredDate, dateList[i]);
appendItem(filteredID, stateID[i]);
appendItem(filteredCase, totalCases[i]);
appendItem(filteredState, usState[i]);
}
}
}
I have question about getting full two years from the current date. So what i did id get the current month using the new date function and used the for loop to print each of the month. But, i cant really get it to work.... I will post the code that i did below. I would be really appreciate it if anyone can tell me the logic or better way of doing it.
For example: if today current date is august it store into an array from 8 / 2020 9/ 2020 ..... 12/ 2020, 1/2021 and goes to another year to 8/2022.
var d = new Date();
var year = d.getFullYear();
var dateStr;
var currentYear;
var storeMonthYear = [];
for(var i = 1; i <= 24; i++){
dateStr = d.getMonth() + i
currentYear = year;
if(dateStr > "12"){
dateStr = dateStr - 12
// currentYear = year;
// if(currentYear){
// }
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else if(dateStr > "24"){
storeMonthYear[i] = dateStr + "/" + (currentYear + 1);
}
else{
storeMonthYear[i] = dateStr + "/" + currentYear;
}
storeMonthYear[i] = d.getMonth() + i
}
export const settlementPeriod = [
{
MonthYearFirstRow1: storeMonthYear[1],
MonthYearFirstRow2: storeMonthYear[2],
MonthYearFirstRow3: storeMonthYear[3],
MonthYearFirstRow4: storeMonthYear[4],
MonthYearFirstRow5: storeMonthYear[5],
MonthYearFirstRow6: storeMonthYear[6],
MonthYearFirstRow7: storeMonthYear[7],
MonthYearFirstRow8: storeMonthYear[8],
MonthYearFirstRow9: storeMonthYear[9],
MonthYearFirstRow10: storeMonthYear[10],
MonthYearFirstRow11: storeMonthYear[11],
MonthYearFirstRow12: storeMonthYear[12],
MonthYearSecondRow13: storeMonthYear[13],
MonthYearSecondRow14: storeMonthYear[14],
MonthYearSecondRow15: storeMonthYear[15],
MonthYearSecondRow16: storeMonthYear[16],
MonthYearSecondRow17: storeMonthYear[17],
MonthYearSecondRow18: storeMonthYear[18],
MonthYearSecondRow19: storeMonthYear[19],
MonthYearSecondRow20: storeMonthYear[20],
MonthYearSecondRow21: storeMonthYear[21],
MonthYearSecondRow22: storeMonthYear[22],
MonthYearSecondRow23: storeMonthYear[23],
MonthYearSecondRow24: storeMonthYear[24]
},
];
Create the date from today, get the month and year. Iterate from 0 to 24 for now till in 24 months. If month is 12 than set month to 0 and increment the year. Push the new datestring. Increment the month for the next step.
Note: Beacsue JS counts months form 0-11 you had to add for the datestring 1 for the month and make the change of year at 12 and not 13.
let date = new Date();
let year = date.getFullYear();
let month = date.getMonth();
let res=[];
for (let i=0; i<=24; i++) {
if (month===12) {
month = 0;
year++;
}
res.push(month+1 + '/' + year);
month++;
}
console.log(res);
Here you go, you get an array of strings like "8/2020","9/2020" etc from starting month to the last month including both( in total 25 months).
If you don't want to include last month just delete +1 from for loop condition.
let currentDate = new Date();
let settlementPeriod = [];
let numberOfMonths = 24;
for(let i=0;i<numberOfMonths+1;i++){
settlementPeriod.push(currentDate.getMonth()+1+"/"+currentDate.getFullYear()); //We add current date objects attributes to the array
currentDate = new Date(currentDate.setMonth(currentDate.getMonth()+1)); //Every time we add one month to it
}
console.log(settlementPeriod);
There are a couple of things that stick out in your code sample:
You're comparing strings and numbers (e.g. dateStr > "12"). This will lead to some weird bugs and is one of JS's most easily misused "features". Avoid it where possible.
You increment the year when you reach 12 months from now, rather than when you reach the next January
You're overwriting your strings with this line storeMonthYear[i] = d.getMonth() + i so your array is a bunch of numbers rather than date strings like you expect
Here's a code sample that I think does what you're expecting:
function next24Months() {
const today = new Date()
let year = today.getFullYear()
let monthIndex = today.getMonth()
let dates = []
while (dates.length < 24) {
dates.push(`${monthIndex + 1}/${year}`)
// increment the month, and if we're past December,
// we need to set the year forward and the month back
// to January
if (++monthIndex > 11) {
monthIndex = 0
year++
}
}
return dates
}
In general, when you're dealing with dates, you're probably better off using a library like Moment.js - dates/times are one of the most difficult programming concepts.
While #Ognjen 's answer is correct it's also a bit waseful if your date never escapes its function.
You don't need a new date every time:
function getPeriods(firstMonth, numPers){
var d = new Date(firstMonth.getTime()); // clone the start to leave firstMonth alone
d.setDate(1); // fix after #RobG
var pers = [];
var m;
for(var i = 0; i< numPers; i++){
m = d.getMonth();
pers.push(`${m+ 1}/${d.getFullYear()}`)
d.setMonth(m + 1); // JS dates automatically roll over. You can do this with d.setDate() as well and when you assign 28, 29, 31 or 32 the month and year roll over automatically
}
return pers;
}
Im building a mini calendar that just displays the current month, I have figured out how to map out the calendar, here is the code:
Code:
var month = moment(),
index = 0,
maxDay = month.daysInMonth(),
start = month.startOf("month"),
offset = (start.isoWeekday() - 1 + 7) % 7; // start from monday
var week = []; // holds the weeks
var days = []; // holds the days
do {
var dayIndex = index - offset;
if(dayIndex >= 0 && dayIndex < maxDay){
days.push({
number: dayIndex + 1,
isPast: null, // stuck here boolean
isToday: null // stuck here boolean
})
}
if(index % 7 === 6){
week.push(days);
console.log(week);
days = [];
if (dayIndex + 1 >= maxDay) {
break;
}
}
index += 1;
} while(true);
This works fine, the only issue Im having is to figure out if the day is today or its in the past?
the code is here also: https://jsfiddle.net/chghb3Lq/3/
Moment has isBefore, isAfter and isSame functions to compare moments and as the docs says:
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
There are a couple of things in your code that you can achieve in a simple way using momentjs instead of reimplementing by yourself:
To loop from the first day of the month until the last day you can use:
startOf('month') and endOf('month') as limit of the loop
add(1, 'day') to increment loop index
isBefore as loop condition
Use date() to get date of the month (1-31)
Use day() to get day of the week (0 => Sunday, ... 6 => Saturday); or weekday() to get day of the week locale aware.
Using these suggestions your code could be like the following:
var day = moment().startOf('month');
var endOfMonth = moment().endOf('month');
var week = [];
var month = [];
while( day.isBefore(endOfMonth) ){
week.push({
number: day.date(),
isPast: moment().isAfter(day, 'day'),
isToday: moment().isSame(day, 'day')
});
if( day.day() === 0 ){
month.push(week);
week = [];
}
day.add(1, 'day');
}
console.log(month);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Use moment methods like isSame() , isBefore(), isSameOrBefore() etc.
They each allow setting comparison units like year month week day hour minute second
See Query Section of moment docs
I am trying to get the date for the next instance of a weekday after a given date. The weekday may be any day from Monday through Sunday. I am using the Moment.js library but there doesn't seem to be a simple way to achieve what I am after.
This is what I have so far but it's not returning the date I want:
// competition.startDate = 2016-02-10 (Wednesday)
var startDate = moment(competition.startDate);
...
for (m = 0; m < matchesPerRound; m++) {
var date;
...
// matchTime[m].day = 3 (Wednesday)
date = startDate.startOf('week').add(7, 'days').subtract(matchTime[m].day, 'days');
console.log(date.format('YYYY-MM-DD'));
// Actual Output = 2016-02-11
// Expected Output = 2016-02-10
...
}
With the example above, I need it returning 2016-02-15 as this is the next Monday after 2016-02-10. This is no problem, and I can get that date. My problem is that I need something more dynamic, as matchTime[m].day could be any weekday number. For example, if matchTime[m].day = 3 // Wednesday, it should just return the same startDate 2016-02-10 as this is a Wednesday.
I'm trying to avoid conditional statements if possible, but I am wondering if Moment.js has the functionality out of the box to produce these results.
UPDATE
I've come up with a solution, and it's working with my requirements, but I feel it's very messy. Does someone else have a cleaner, more concise solution?
var date;
var startDate = moment(competition.startDate);
var proposedDate = moment(startDate).startOf('isoweek').add(matchTimes[0].day - 1, 'd');
if ( startDate.isAfter(proposedDate) ) {
date = startDate.startOf('isoweek').add(7 + Number(matchTimes[0].day) - 1, 'd');
} else {
date = startDate.startOf('isoweek').add(matchTimes[0].day - 1, 'd');
}
I don't know about moment.js, but it seems rather complex for something rather simple.
function firstMatchingDayOfWeek(day, date) {
var delta = date.getDay() - day,
result = new Date(date);
if (delta) {
result.setDate(result.getDate() + ((7 - delta) % 7));
}
return result;
}
I think the code is rather self-explanatory (don't we all ;-) ), but in order to clarify the steps:
firstMatchingDayOfWeek(day, date) > call the function specifying the day of week (0-6) and a date object
delta = date.getDay() - day > calculate how many days the date needs to shift in order to reach the same day of week
result = new Date(date) > create a new Date instance based on the input (so you get to preserve the original date)
result.setDate(result.getDate() + ((7 - delta) % 7)) > set the date part (day of month) to a week minus the delta, modulo a week (as delta can be negative and you want the first occurrence of the same day)
function firstMatchingDayOfWeek(day, date) {
var delta = date.getDay() - day,
result = new Date(date);
if (delta) {
result.setDate(result.getDate() + ((7 - delta) % 7));
}
return result;
}
// tests
for (var i = 1; i < 28; ++i){
var check = new Date('2016-02-' + ('00' + i).substr(-2)),
output = document.querySelector('#out')
.appendChild(document.createElement('pre')),
log = [];
log.push('input: ' + check);
for (var day = 0; day <= 6; ++day) {
var next = firstMatchingDayOfWeek(day, check);
log.push(day + ' > ' + next);
}
output.innerText = log.join('\n');
}
pre {
border: 1px solid gold;
}
<div id="out"></div>
Here's a possible answer too using momentjs (assumes match days will be 0 (sunday) - 6):
var startDate = moment(competition.startDate);
var matchDay = Number(matchTimes[0].day);
var daysToAdd = Math.ceil((startDate.day() - matchDay) / 7) * 7 + matchDay;
var proposedDate = moment(startDate).startOf('week').add(daysToAdd, 'd');
This is a pure JS version:
Logic
Find current day.
Find days to add to get to start of next week.
Get day number for the day to find date.
Compute date with this date.
JSFiddle.
function claculateNextDate() {
var date = new Date();
var nextDay = document.getElementById("dayOfWeek").value;
var day = date.getDay();
var noOfDaysToAdd = (7 - day) + parseInt(nextDay);
date.setDate(date.getDate() + noOfDaysToAdd);
document.getElementById("result").innerHTML = date.toDateString();
}
<select id="dayOfWeek">
<option value="0">Sunday</option>
<option value="1">Monday</option>
<option value="2">Tuesday</option>
<option value="3">Wednesday</option>
<option value="4">Thursday</option>
<option value="5">Friday</option>
<option value="6">Saturday</option>
</select>
<button onclick="claculateNextDate()">Calculate Next Date</button>
<p id="result"></p>
My solution
var weekDayToFind = moment().day('Monday').weekday() //change monday to searched day name
var givenDate = moment('2016-02-10') // pass the given date
var searchDate = moment(givenDate)
while (searchDate.weekday() !== weekDayToFind){
searchDate.add(1, 'day');
}