I want to make a week planner, that displays all days of the week and the according date to it. And of course the month.
(Unfortunately, I don't have enough reputation to post a screenshot of what my calendar looks like.)
My JavaScript code looks like this. I found a part of it from Stack Overflow.
function calendar() {
var today = new Date();
var currYear = today.getFullYear();
var currMonth = today.getMonth();
var currWeek = today.getWeek()-1;
var firstDateOfMonth = new Date(currYear, currMonth, 1);
var firstDayOfMonth = firstDateOfMonth.getDay();
var firstDateOfWeek = new Date(firstDateOfMonth);
firstDateOfWeek.setDate(
firstDateOfWeek.getDate() +
(firstDayOfMonth ? 7 - firstDayOfMonth : 0)
);
firstDateOfWeek.setDate(
firstDateOfWeek.getDate() +
7 * (currWeek-1)
);
var dateNumbersOfMonthOnWeek = [];
var datesOfMonthOnWeek = [];
for (var i = 0; i < 7; i++) {
dateNumbersOfMonthOnWeek.push(
firstDateOfWeek.getDate());
datesOfMonthOnWeek.push(
new Date(+firstDateOfWeek));
firstDateOfWeek.setDate(
firstDateOfWeek.getDate() + 1);
}
setText('month-year', monthArray[currMonth] + " " + currYear);
setText('Mo', dateNumbersOfMonthOnWeek[0]);
setText('Di', dateNumbersOfMonthOnWeek[1]);
setText('Mi', dateNumbersOfMonthOnWeek[2]);
setText('Do', dateNumbersOfMonthOnWeek[3]);
setText('Fr', dateNumbersOfMonthOnWeek[4]);
setText('Sa', dateNumbersOfMonthOnWeek[5]);
setText('So', dateNumbersOfMonthOnWeek[6]);
};
function setText(id, val) {
if(val < 10){
val = '0' + val;
}
document.getElementById(id).innerHTML = val;
};
window.onload = calendar;
It works as it displays the correct days for the weekdays (so, 08 for this Monday, 09 for this Tuesdays, etc) and also the month is the correct one.
The question now is how to get the previous or next week? When I click on the "<" arrow I want to see the previous week. So how should I write the loop, which parameters does the method need, etc. I am very thankful for every hint, link, example etc.
For next week-
var today = new Date();
var nextweek = new Date(today.getFullYear(), today.getMonth(), today.getDate()+7);
for more detail check following link:-
how to get next week date in javascript
Related
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;
}
I'm trying to create calendar and I tried below.
function displayCalendar() {
var dateNow = new Date();
var month = dateNow.getMonth();
var counter = 1;
var nextMonth = month + 1;
var prevMonth = month -1;
var day = dateNow.getDate();
var year = dateNow.getFullYear();
var dayPerMonth = ["31","28","31","30","31","30","31","31","30","31","30","31"]
// days in previous month and next one , and day of week.
var nextDate = new Date(nextMonth +' 1 ,'+year);
var weekdays = nextDate.getDay();
var numOfDays = dayPerMonth[month];
var ul = document.getElementById('dates');
var monthInt = month + 1;
var currentMonth = document.getElementById('currentMonth');
monthInt.toString().length === 1 ? currentMonth.innerHTML = "0" + monthInt : currentMonth.innerHTML = monthInt;
// add empty li
while (weekdays > 0) {
var li = document.createElement('li');
ul.appendChild(li);
weekdays--;
}
while (counter <= numOfDays) {
var li = document.createElement('li');
li.innerHTML = counter;
ul.appendChild(li);
counter++;
}
}
It works fine but when I change month to August like this
var month = dateNow.getMonth() + 1;
first date starts at Sunday. It should start at Wednesday.
I think this code is not working
while (weekdays > 0) {
var li = document.createElement('li');
ul.appendChild(li);
weekdays--;
}
In chrome it works and starts at Wednesday correctly.
Anyone know why it's not working?
Thank you in advance!
I think the problem is your date format. Chrome is being more generous in parsing the date you're giving it, which is a string that looks like "7 1,2018". Chrome accepts that as a valid date, Safari doesn't. If you made sure you put slashes between the month, date, and year, like "7/1/2018" it would work better.
I think the problem is that in calculating nextMonth to put in your string you are assuming months in dates in js start with 1. But they start with 0. So your date now get month is giving you 6, not 7, and when you add 1 you are getting 7, not 8. Add 2 and you will get Wednesday like you want.
Specifically you need var nextMonth = month + 2;
I tested this in Firefox. I agree with the other posted answer about not loving the date format.
Also, you appear not to use prevMonth. You should remove it. Or if it you need for something, it should not have the -1.
Finally, you are going to want to revisit your index into the daysPerMonth array. If you want the number of days in next month, it is off.
As kshetline said, the problem was date format.
Changed this code
var nextDate = new Date(nextMonth +' 1 ,'+year);
var weekdays = nextDate.getDay();
to
var nextDate = new Date(year, month, 1);
var weekdays = nextDate.getDay();
then it worked fine!
Before I am using angularjs-DatePicker from this npm.
Here,I am able to select the date from the date picker.But now I have to fields as FromDate and ToDate which means the week StartDate and EndDate should show when any date pick in that week.
Ex: Like in Calender 01-08-2017 Start on Tue, So whenever Selects Any date from 01 to 05 then the two fields should show as FromDate as 01 and TODate as 06 and in the same whenever the user selects the 31-07-2017 the the Two fields should show as 30 and 31 of july.
I have an idea to achieve the ToDate from FromDate Calender control onchange event in DotNet as like below mentioned code
Convert.ToDouble(objstart.DayOfWeek)).ToString("dd-MM-yyyy")
But how to achieve this usecase in the angularjs.
Thanks
Ok, so what I'd do is to calculate different dates, and take the min/max depending on the start or end of the week.
Here:
//Use the date received, UTC to prevent timezone making dates shift
var pickedDate = new Date("08-03-2017UTC");
var startSunday = new Date(pickedDate);
startSunday.setDate(pickedDate.getDate() - pickedDate.getDay());
var startMonth = new Date(pickedDate);
startMonth.setDate(1);
var startDate = Math.max(startMonth,startSunday);
console.log("Start:" , new Date(startDate));
var endSaturday = new Date(pickedDate);
endSaturday.setDate(pickedDate.getDate() + (7-pickedDate.getDay()));
var endMonth = new Date(pickedDate);
endMonth.setMonth(pickedDate.getMonth()+1);//Add a month
endMonth.setDate(0);// to select last day of previous month.
var endDate = Math.min(endMonth,endSaturday);
console.log("End" , new Date(endDate));
The trick was to play with the dates, find all the possible start and end dates, then choose the right one with Math.min and Math.max which will compare the dates using their timestamp.
There is very good Library available in JavaScript to handle Date Manipulations.
https://github.com/datejs/Datejs
There is a method
Date.parse('next friday') // Returns the date of the next Friday.
Date.parse('last monday')
Using these method you can get the start and ending date of the week based on the current week.
I hope that it will help.
You can simply achieve this using the library moment. There are a lot of useful functions in this library.
var selectedDate = moment('Mon Aug 10 2017');
//If you want to get the ISO week format(Monday to Sunday)
var weekStart = selectedDate.clone().startOf('isoweek').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('isoweek').format('MMM Do');
//If you want to get the Sunday to Saturday week format
var weekStart = selectedDate.clone().startOf('week').format('MMM Do');
var weekEnd = selectedDate.clone().endOf('week').format('MMM Do');
No need angular directive here, you could use the JavaScript extension which is below.
//get week from date
Date.prototype.getWeekNumber = function (weekstart) {
var target = new Date(this.valueOf());
// Set default for weekstart and clamp to useful range
if (weekstart === undefined) weekstart = 1;
weekstart %= 7;
// Replaced offset of (6) with (7 - weekstart)
var dayNr = (this.getDay() + 7 - weekstart) % 7;
target.setDate(target.getDate() - dayNr + 0);//0 means friday
var firstDay = target.valueOf();
target.setMonth(0, 1);
if (target.getDay() !== 4) {
target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstDay - target) / 604800000);;
};
//get date rance of week
Date.prototype.getDateRangeOfWeek = function (weekNo, weekstart) {
var d1 = this;
var firstDayOfWeek = eval(d1.getDay() - weekstart);
d1.setDate(d1.getDate() - firstDayOfWeek);
var weekNoToday = d1.getWeekNumber(weekstart);
var weeksInTheFuture = eval(weekNo - weekNoToday);
var date1 = angular.copy(d1);
date1.setDate(date1.getDate() + eval(7 * weeksInTheFuture));
if (d1.getFullYear() === date1.getFullYear()) {
d1.setDate(d1.getDate() + eval(7 * weeksInTheFuture));
}
var rangeIsFrom = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
d1.setDate(d1.getDate() + 6);
var rangeIsTo = eval(d1.getMonth() + 1) + "/" + d1.getDate() + "/" + d1.getFullYear();
return { startDate: rangeIsFrom, endDate: rangeIsTo }
};
Your code can be look like this
var startdate = '01-08-2017'
var weekList = [];
var year = startdate.getFullYear();
var onejan = new Date(year, 0, 1);//first january is the first week of the year
var weekstart = onejan.getDay();
weekNumber = startdate.getWeekNumber(weekstart);
//generate week number
var wkNumber = weekNumber;
var weekDateRange = onejan.getDateRangeOfWeek(wkNumber, weekstart);
var wk = {
value: wkNumber
, text: 'Week' + wkNumber.toString()
, weekStartDate: new Date(weekDateRange.startDate)
, weekEndDate: new Date(weekDateRange.endDate)
};
weekList.push(wk);
I guess there is no directive or filter for this, you need to create one for yourself. you can refer date object from date-time-object
I will explain my question in the code itself. Please see the below code
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var ctdate = (new Date()).getMonth() + 1;// getting current month
var str=new Date().getFullYear()+'';
str= str.match(/\d{2}$/);//current year is 15(as this year is 2015)
var strprev= str-1;//previous year is 14
var dynmonths = new Array();
dynmonths = monthNames.slice(ctdate).concat(monthNames.slice(0, ctdate));
//here the output comes for last 12 months starting from currentmonth-12 (i.e APR in this case) to current month (i.e MAR)
//dynmonths = ["APR","MAY","JUN","JUL","AUG","SEP","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR"];
//I am rotating dynmonths in a for loop to get full dates i.e between (01-APR-14 to 01-MAR-15)
for (var i = 0, length = dynmonths.length; i < length; i++) {
var month = '01-' + dynmonths[i] + '-' + strcurrent;
}
But the problem is that month is taking 14for all the months. Which is wrong. After 01-DEC-14 the next month must be 01-JAN-15, 01-FEB-15 and so on. How to check DEC in for loop and after DEC year must change to year+1
Thanks in advance
use below code it will work.
function ddd()
{
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var ctdate = (new Date()).getMonth() + 1;// getting current month
var str=new Date().getFullYear()+'';
str= str.match(/\d{2}$/);//current year is 15(as this year is 2015)
var strprev= str-1;//previous year is 14
var dynmonths = new Array();
dynmonths = monthNames.slice(ctdate).concat(monthNames.slice(0, ctdate));
//here the output comes for last 12 months starting from currentmonth-12 (i.e APR in this case) to current month (i.e MAR)
//dynmonths = ["APR","MAY","JUN","JUL","AUG","SEP","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR"];
//I am rotating dynmonths in a for loop to get full dates i.e between (01-APR-14 to 01-MAR-15)
for (var i = 0, length = dynmonths.length; i < length; i++) {
if(dynmonths[i]=='JAN')
{
var str = parseInt(str)+parseInt(1);
}
var month = '01-' + dynmonths[i] + '-' + str;
document.writeln(month);
document.write("<br />");
}
}
<body onload="ddd()">
You can declare variable bool = false and check if you on DEC change it to true (or use counter from more then one year):
var monthNames = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
var ctdate = (new Date()).getMonth() + 1;// getting current month
var str=new Date().getFullYear()+'';
str= str.match(/\d{2}$/);//current year is 15(as this year is 2015)
var strprev= str-1;//previous year is 14
var dynmonths = new Array();
dynmonths = monthNames.slice(ctdate).concat(monthNames.slice(0, ctdate));
//here the output comes for last 12 months starting from currentmonth-12 (i.e APR in this case) to current month (i.e MAR)
//dynmonths = ["APR","MAY","JUN","JUL","AUG","SEP","AUG","SEP","OCT","NOV","DEC","JAN","FEB","MAR"];
//I am rotating dynmonths in a for loop to get full dates i.e between (01-APR-14 to 01-MAR-15)
var isPassYear = false;
for (var i = 0, length = dynmonths.length; i < length; i++) {
var month;
if (isPassYear)
//do something
else
month = '01-' + dynmonths[i] + '-' + strcurrent;
if (monthNames[11] == dynmonths[i]) {
isPassYear = true;
}
}
second option is to use Date object and append his month by one each time, if you set append to month number 12 it automatic go to the next year.
Hello i am trying to write the following function to display 7 days of the week
function displaydates(){
// read the string output from the datepicker and
//evalutes which date goes into which cell
var date = document.getElementById("datepicker"); // Mon APR 30 2012 HH:MM:SS
var m = new Date(date.value);
var num = parseInt(m.getDate());
var i = 0;
var days=[];
var x;
for(i; i<=6; i++){
var day= m.setDate(num+i);
var month = m.setMonth(m.getMonth());
x = m.getMonth()+1 + "/" + m.getDate() + "<br />";
days.push(x);
}
document.getElementById("Monday").innerHTML= days[0];
document.getElementById("Tuesday").innerHTML=days[1];
document.getElementById("Wednesday").innerHTML=days[2];
document.getElementById("Thursday").innerHTML=days[3];
document.getElementById("Friday").innerHTML=days[4];
document.getElementById("Saturday").innerHTML=days[5];
document.getElementById("Sunday").innerHTML=days[6];
}
the code works fine as long as it's seven days before the next month.the problem i am having is when the user wants to see the next seven day the function outputs the wrong information
for example
var m = new Date("Apr 30 2012"); / /monday
will make my function out put the following
4/29, 5/30, 7/1, 9/1, 11/2, 1/3, 3/7
again, this only happens on transition to the next month is there and thing i can do to make the month to month transition work in my function
When you call, for example, setDate(32), JavaScript figures out that that requires an additional month and adds it to the date. When you later call setDate(33), it once again adds an extra month...
This solution might work better (some parts are omitted):
var start = new Date();
var days = [];
for(var i = 0; i <= 6; ++i) {
var str = (start.getMonth() + 1) + '/' + start.getDate() + '<br />';
days.push(str);
start.setDate(start.getDate() + 1);
}
Please use the below provided solution
function displaydates(){
// read the string output from the datepicker and
//evalutes which date goes into which cell
var date = document.getElementById("datepicker"); // Mon APR 30 2012 HH:MM:SS
var m = new Date(date.value);
var num = m.getTime();
var i = 0;
var days=[];
var x;
for(i; i<=6; i++){
num+=86400000; //Edited Part
m = new Date(num);
var day= m.getDate();
var month = m.getMonth();
x = month+1 + "/" + day + "<br />";
days.push(x);
}
document.getElementById("Monday").innerHTML= days[0];
document.getElementById("Tuesday").innerHTML=days[1];
document.getElementById("Wednesday").innerHTML=days[2];
document.getElementById("Thursday").innerHTML=days[3];
document.getElementById("Friday").innerHTML=days[4];
document.getElementById("Saturday").innerHTML=days[5];
document.getElementById("Sunday").innerHTML=days[6];
}
Hope this solves your problem.