Generate weekdays from today and a week forward - javascript

I'm generating divs for each day of the week:
var days = new Array("SUN","MON","TUE","WED","THU","FRI","SAT");
function generateWeekdays() {
var d = new Date();
var weekday = d.getDay();
var todaysWeekday = days[weekday];
for (var i = weekday; i < days.length; i++) {
$('<div>' + days[i] + '</div>').appendTo('#weekdayList');
}
}
generateWeekdays();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weekdayList"></div>
This generate (for example) today Wednesday and to Saturday (last index), but how can I make it generate one week, so it generates all the way to Wednesday the next week and stops after that?

You can use the module operator % to keep the indexes in bounds. This will make anything beyond the length of the array loop back so you can just go from 0 to the the array length add today's day to it:
var days = new Array("SUN","MON","TUE","WED","THU","FRI","SAT");
function generateWeekdays() {
var d = new Date();
var weekday = d.getDay();
for (var i = 0; i < days.length; i++) {
console.log(days[(i + weekday) % days.length])
}
}
generateWeekdays()
It's not completely clear in the question but if you want to include next Wednesday, you can loop with for (var i = 0; i < days.length + 1; i++)

Instead of stopping at days.length, you can iterate for 7 (as you want for a week) times, and do a modulo (% 7) operation to get the element from days array.
var days = new Array("SUN","MON","TUE","WED","THU","FRI","SAT");
function generateWeekdays() {
var d = new Date();
var weekday = d.getDay();
var todaysWeekday = days[weekday];
for (var d = weekday, i = 0; i < 7; d++, i++) {
$('<div>' + days[d % 7] + '</div>').appendTo('#weekdayList');
}
}
generateWeekdays();

How about cutting the days (from normal week days) and appending at the end (those days) for your week (that starts from today's day, you have to cut from there)
function getWeekDaysFromToday() {
let days = ["SUN","MON","TUE","WED","THU","FRI","SAT"];
return days.concat( days.splice (0,new Date().getDay()));
}
console.log(getWeekDaysFromToday())

In your for loop instead of iterating until days.length you want to just do 7 iterations and cycle back to the beginning of the array. If you set up a counter that will iterate 7 times and add an if statement in the loop to loop back to the beginning of the array if you reach the end, that should work.

How about adding another iteration, to take into account of what today is in relation to the index of the array?
var days = new Array("SUN","MON","TUE","WED","THU","FRI","SAT");
function generateWeekdays() {
var d = new Date();
var weekday = d.getDay();
var todaysWeekday = days[weekday];
for (var i = weekday; i < days.length; i++) {
$('<div>' + days[i] + '</div>').appendTo('#weekdayList');
}
for(var i = 0; i < days.indexOf(days[weekday]); i++){
$('<div>' + days[i] + '</div>').appendTo('#weekdayList');
}
}
generateWeekdays();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weekdayList"></div>

Here is a quick implementation that I threw together. I used a do/while loop because you know you are always going to execute at least once. I Also limit the loop to the number of days you want to display so you could just increment that to show additional days. I also used the % (Modulus) with count and weekday to get the right value from the array.
var days = new Array("SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT");
function generateWeekdays() {
var d = new Date();
var weekday = d.getDay();
var todaysWeekday = days[weekday];
let count = 0;
do {
$('<div>' + days[(count + weekday) % days.length] + '</div>').appendTo('#weekdayList');
count++;
} while (count < 7)
}
generateWeekdays()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weekdayList">
</div>

I took a different approach to the question. Rather than checking incrementally if I have processed 7 days, I concatenated the days list to itself, so it would be 14 days, and then starting at the current day, I splice out 7 days so I have a week, and for each of them I create a div.
I also changed it to collect the divs and append them all at the end for some performance gains.
var days = new Array("SUN","MON","TUE","WED","THU","FRI","SAT");
function generateWeekdays() {
var oneWeekOfDays = days.concat(days).splice(new Date().getDay(), 7).map(function(day){
return '<div>'+ day +'</div>';
});
$('#weekdayList').append(oneWeekOfDays);
}
generateWeekdays();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weekdayList"></div>

let dataArr = []; //empty array
let days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
];
let d = new Date();
let weekday = d.getDay(); // it'll return day number like monday is 1
for (var i = 0; i < 7; i++) {
dataArr.push(days[(i + weekday) % days.length]); //push 7 days from today in array
}
console.log(dataArr)

Related

How to find the days of the week in JavaScript

I am trying to find the weekdays from today to Sunday. Since today is Monday I want to display the dates from Monday till Sunday, but tomorrow, I want my programme works from Tuesday to Sunday.
dateSets() {
let firstDayOfWeek = "";
let dates = [];
firstDayOfWeek = new Date();
let sunday = new Date();
sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
const diff = sunday.getDate() - firstDayOfWeek.getDate();
dates.push(new Date());
for (let i = 0; i < diff; i++) {
dates.push(
new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + 1))
);
}
return dates;
},
And here is the other function to find the date of the week:
getDateOfWeek(week, year) {
let simple = new Date(year, 0, 1 + (week - 1) * 7);
let dow = simple.getDay();
let weekStart = simple;
if (dow <= 4) weekStart.setDate(simple.getDate() - simple.getDay() + 1);
else weekStart.setDate(simple.getDate() + 8 - simple.getDay());
return weekStart;
},
But it doesn't work that I expected, in dataset, only Monday is being displayed but not other dates and I don't understand the reason. If you can help me with this, I would be really glad.
Thanks...
function getWeekDates(){
const dates = [new Date()]; // today
const curr = new Date();
const remDaysCount = 7-curr.getDay();
for(let i=1; i<= remDaysCount; i++){
// increase current Date by 1 and set to current Date
const nextDate = curr.setDate(curr.getDate()+1);
dates.push(new Date(nextDate));
}
return dates;
}
console.log(getWeekDates());
This is kind of your choice but if you install NodeJS and open your folder in cmd and type in 'npm init' and 'npm I days' and open your editor and type in
var days = require('days');
console.log(days); // ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
console will reveal all of the days of the week and if you want a specific day you can do the following
var days = require('days');
console.log(days[0]); //Sunday
if you need help with installing NodeJS watch a YouTube video or reply to this comment I will help
let firstDayOfWeek = "";
let dates = [];
firstDayOfWeek = new Date();
let sunday = new Date();
sunday.setDate(sunday.getDate() - sunday.getDay() + 7);
//const diff = sunday.getDate() - firstDayOfWeek.getDate();
//Try this code
var timeDiff = Math.abs(sunday.getTime() - firstDayOfWeek.getTime());
var diff = Math.ceil(timeDiff / (1000 * 3600 * 24));
dates.push(new Date());
for (let i = 0; i < diff; i++) {
dates.push(
new Date(firstDayOfWeek.setDate(firstDayOfWeek.getDate() + 1))
);
}
return dates;
Your issue is here:
const diff = sunday.getDate() - firstDayOfWeek.getDate()
Currently the date is 27 Sep and next Sunday is 3 Oct so diff is -4 and the for loop test i < diff is false from the start. Consider using a loop and increment the date from today until it gets to Sunday.
function getDaysToSunday(date = new Date()) {
let d = new Date(+date);
let result = [];
do {
result.push(new Date(+d));
d.setDate(d.getDate() + 1);
} while (d.getDay() != 1)
return result;
}
console.log(getDaysToSunday().map(d=>d.toDateString()));

How to check conditions for every day of a year in loop?

I got lot of selected data from fullcalendar. I need to get those selected date from one whole year. How to check that in for loop?
I tried few answers to add days one by one to my condition from some answers ,but its not working for me.
Here is my code I tried:
var t=$(#dttbl).datatable();
var arr = new Array();
var date = new Date(),
var Id = 1;
var d = date.getDate(),
month = date.getMonth(),
year = date.getFullYear()
var day1 = y + '-01-01';
var day365 = y + '-12-31';
for (i = day1; i < day365; day1.setdate(day1.getdate() + 1)) {
if (($(i.cell).css('backgroundColor', 'blue'))) {
arr.push(([Id,i,'test']));
Id++;
}
}
for (i = 0; i < arr.length; i++) {
t.row.add([
arr[i][0],
arr[i][1],
arr[i][2]
]).draw();
}
I tried this getdate(), day1.add(1).day(); , day1=moment(day1).add(1, 'days') to add one by one day to check my condition for full year? These are not working for me. Is there any other way to do it?
You can use the following as #mplungjan commented.
var arr = [];
var date = new Date('01-01-2019');
var DAY = 1000 * 60 * 60 * 24;
var day1 = date.getTime();
var day365 = day1+ 365*DAY;
var iDay = day1;
while(iDay < day365){
// pushing the value in arr for example.
arr.push(new Date(iDay));
// do your logic
iDay = iDay + DAY;
}
You can use daysInMonth function of moment.js to find how many days in each month. After that you can create your array.
var dates = [];
var year = new Date().getFullYear();
for (var i = 1, l = 12; i <= l; i++){
var daysInMonth = moment("2012-" + i, "YYYY-M").daysInMonth();
console.log("month : " + i)
console.log("days in month : " + daysInMonth)
for (i1 = 1, l1 = daysInMonth; i1 <= l1; i1++) {
dates.push(year + "-" + i + "-" + i1)
}
}
console.log(dates);

How to get days between date range by using javascript or jquery

In a form, I define a start date, an end date, and weekdays
Example:
Start date: 2017-02-07
End date: 2017-03-07
Weekdays: Monday and Thursday
Now I want to get all Mondays and Thursdays between start date and end date by using Javascript or jQuery.
Who can help me?
Thanks...
Simple code. Codepen
var startDate = new Date('2017-02-07');
var endDate = new Date('2017-02-17');
var monday = [];
var thursday = [];
for (var d = new Date(startDate); d <= new Date(endDate); d.setDate(d.getDate() + 1)) {
if(d.getDay()==1)
monday.push(d);
else if(d.getDay()==4)
thursday.push(d);
}
You can parse date and iterate over increment 1 day and getDay to map with sun(0) to sat(6)
var startDate = new Date("2017-02-07");
var endDate = new Date("2017-03-07");
var totalMon = [];
var totalThu = [];
for (var i = startDate; i <= endDate; ){
if (i.getDay() == 1){
totalMon.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
if (i.getDay() == 4){
totalThu.push(i.getFullYear() + "-" + (i.getMonth()+1) + "-" + i.getDate());
}
i.setTime(i.getTime() + 1000*60*60*24);
}
console.log(totalMon.length ,totalMon);
console.log(totalThu.length ,totalThu);
Below code finds number of Mondays. You can modify it to calculate any day. It basically finds the difference of days in two dates. Divide it by 7 (this is the number of times everyday will come). Now for pending days loop through the dates and check if a desired day comes in this loop.
var startDate = new Date(2017, 02, 07);
var endDate = new Date(2017, 03, 07);
var dayDiff = Math.round((endDate-startDate)/(1000*60*60*24));
var numberOfMondays = Math.floor(dayDiff/7);
var remainingDays = dayDiff%7;
for(i=0;i<remainingDays;i++)
{
var dateObj = new Date();
dateObj.setDate(endDate.getDate() - i);
if(dateObj.getDay() == 2)
numberOfMondays=numberOfMondays+1;
}
alert(numberOfMondays);
PS : the other two answer are looping through all the dates. I will not suggest this. In code above the number of iterations in loop will never exceed 6 irrespective of the difference in dates.

How to loop through dates using for and while loops

I would like to be able to loop through an XML file to find the earliest and latest date. Once those dates are found, I want to loop through the records again and compare the month and year from each record to the date that is being passed in. If the month and year match, then the count is increased by one. After the loop goes through all of the records, the date and count are added to an array, the date being passed in is then increased by one, and the loops runs again. The while loop continues to run until the date being increased is greater than the latest record date.
MY CODE:
var record=xmlDoc.getElementsByTagName("record");
var maxDate = 0;
// Loop through all of the records to find the latest date
for(var i=0; i<record.length; i++)
{
var tempMaxDate = record[i].getElementsByTagName("visit_date")[0].childNodes[0].nodeValue;
if(tempMaxDate > maxDate)
{
maxDate = tempMaxDate;
}
}
var minDate = 99999999999999;
// Loop through all of the records to find the earliest date
for(var i=0; i<record.length; i++)
{
var tempMinDate = record[i].getElementsByTagName("visit_date")[0].childNodes[0].nodeValue;
if(tempMinDate < minDate)
{
minDate = tempMinDate;
}
}
var minDateGraph = minDate;
var count = 0;
var data = [];
// Loop until the minimum date is greater than the maximum
while(minDate <= maxDate)
{
var tempMinDate2 = new Date(0);
tempMinDate2.setMilliseconds(minDate);
minDate = tempMinDate2;
// Loop through all of the records
// If the month and year of minDate match the record then the count is increased
for(var i=0; i<record.length; i++)
{
var tempVisitDate = record[i].getElementsByTagName("visit_date")[0].childNodes[0].nodeValue;
var visitDate = new Date(0);
visitDate.setMilliseconds(tempVisitDate);
if((visitDate.getMonth() == minDate.getMonth()) && (visitDate.getFullYear() == minDate.getFullYear()))
{
count += 1;
}
}
var tempData = [minDate, count];
data.push(tempData);
var month = minDate.getMonth();
var year = minDate.getFullYear();
// Increase the minDate by one month
if(month == 12)
{
year += 1;
month = 1;
}
else
{
month += 1;
}
var tempMinDate3 = new Date(year, month, 1).getTime();
minDate = tempMinDate3;
}
The problem is when I run my current code, the browser crashes. I think I am running into an infinite loop, but I cannot find what is causing it. I would appreciate any suggestions. Thanks!

Javascript function , which takes a month/date and disply 12 months/dates back

Is there any javascript function which takes one input parameter (e.g 04/2014 ) and return
12 months and dates with the same format
(e.g 04/2013.........................................04/2014)
i have this one
function calcFullMonth(startDate) {
//copy the date
var dt = new Date(startDate);
dt.setMonth(dt.getMonth() - 1);
return dt;
}
The logic that i have is this .But it gives me only one month back
I need to get 12 months and 1 year back and display them as you see second e.g.
Thanks
Just call your original function as many times as you need, and store them in an array.
function calcFullMonth(startDate, num) {
var months = [];
for (var i = 0; i < num; i++) {
var dt = new Date(startDate);
dt.setMonth(dt.getMonth() + i);
months[i] = dt;
}
return months;
}
For example, to get the current month until this month next year, use num = 13
console.log(calcFullMonth(new Date(), 13));
fiddle
Try the following function
function Get12MonthBack(input) {
var year = input.split("/")[1];
var month = input.split("/")[0];
var d = new Date(year, month);
d.setMonth(d.getMonth()-12);
return (d.getMonth().toString().length == 1 ? "0" + d.getMonth() : d.getMonth()) + "/" + d.getFullYear();
}
Tests
Get12MonthBack("03/2011")
"03/2010"
Get12MonthBack("11/2012")
"11/2012"

Categories

Resources