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!
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;
}
Here is my 2 date
var startdate = '11-12-2016';
var stopdate = '13-12-2016';
I want to loop between these two dates. So, i did like this
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
while(startMedicine <= stopMedicine){
console.log(startdate)
}
But i am getting unlimited loops running in browser.
How can i do this.
Note :
I don't want to use jQuery for this one.
If the start and end date is same it should loop only once and the input date will be always d/m/y format. What is the mistake in my code. Pls help
Update :
I have mistaken the date format, my date format is d-m-y. How can i do this for one..
Increment date by one day per iteration using getDate
startdateArr = startdate.split('-');
stopdateArr = stopdate.split('-');
var startMedicine = new Date(startdateArr[2],startdateArr[1]-1,startdateArr[0]);
var stopMedicine = new Date(stopdateArr[2],stopdateArr[1]-1,stopdateArr[0]);
// thanks RobG for correcting on month index
while(startMedicine <= stopMedicine){
var v = startMedicine.getDate() + '-' + (startMedicine.getMonth() + 1) + '-' + startMedicine.getFullYear();
console.log(v);
startMedicine.setDate(startMedicine.getDate()+1);
}
In js month indexing starts at 0 so nov is 10 dec. is 11 and like so that's why i use getMonth() + 1
`
main problem is that you are not increasing your date.
here is the solution
var startdate = '11/12/2016';
var stopdate = '11/13/2016';
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
var currentMedicine = startMedicine;
var dayCount = 0;
while(currentMedicine < stopMedicine){
currentMedicine.setDate(startMedicine.getDate() + dayCount);
// You can replace '/' to '-' this if you want to have dd-mm-yyyy instead of dd/mm/yyy
var currentDate = currentMedicine.getDate() + '/' + (currentMedicine.getMonth() + 1) + '/' + currentMedicine.getFullYear(); // in dd/mm/yyyy format
console.log(currentDate);
dayCount++;
}
You can make use of moment js and moment js duration. Its for duration purpose only. It very easy and meant for same.
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
I've got this:
var lDate = document.getElementById('txtLeaveDate');
var rDate = document.getElementById('txtReturnedDate');
Err...javascript so how do I assign the value of txtLeaveDate to a date variable
I tried:
var myDate = new Date(lDate.value);
But this assigns some long value....
I can do it if I try:
var today = new Date();
var day2 = new Date();
day2.setDate(today.getDate() + 30);
But the issue is I need to get the date from txtLeaveDate not by a date variable
edit complete code
var theLDate = new Date(lDate.value);
var theRDate = new Date(rDate.value);
//check if return date is a sunday, if it is no need
//to do anything,
//else make it a sunday
while (theRDate.getDay() != 0)
theRDate.setDate(theRDate.getDate() + 1);
//at this point RDate is a sunday...
while(theLDate.valueOf() <= theRDate.valueOf())
{
if(theLDate.getDay() == 0)
{ //sunday
var li = document.createElement('li');
li.setAttribute('id', ['liID' + count]);
var month = theLDate.getMonth();
var day = theLDate.getDate();
var year = theLDate.getFullYear();
var theDay = month + '/' + day + '/' + year + ' (Sunday)';
li.innerHTML = theDay;
ul.appendChild(li);
}
theLDate.setDate(theLDate.getDate() + 1);
count++;
}
But when I pick 2 dates in my calendar like so:
if I try that and say alert(theLDate.valueOf()); it returns
1309924800000
That's because that is the value of a Date object, measured in milliseconds since 1/1/1970 00:00:00, in this case corresponding to Wed Jul 6 04:00:00 2011 UTC.
Try using .toString() instead and you'll see the corresponding date in a human readable format.
The problem with your dates appearing to be in June is because the getMonth() function for odd reasons returns the month zero based, i.e. January == 0.
You need to use .innerHTML, otherwise you are not returning the text in the element.
var lDate = document.getElementById('txtLeaveDate').innerHTML;
var myDate = new Date(lDate);
document.write(myDate);
http://jsfiddle.net/jasongennaro/ua85k/
Months returned by the someDate.getMonth method are zero-indexed (from 0 to 11). So if using them to create a string add 1!
var month = theLDate.getMonth() + 1;
I have this code:
var fd=1+self.theDate.getMonth() +'/'+ today+'/'+self.theDate.getFullYear();
It works, but it's format is Month, Day, Year.
I need to change it to: Day, Month Year.
So, I tried this:
var fd=1+today +'/'+ self.theDate.getMonth()+'/'+self.theDate.getFullYear();
Now, my change does not work. Is it that I have not done it properly or is my change right?
Thanks
I expect the correct answer is this:
var fd=today +'/'+ (self.theDate.getMonth() + 1) +'/'+self.theDate.getFullYear();
This leaves today alone, and groups Month so that it does a proper number addition instead of string concatenation.
var theDate = new Date();
var today = theDate.getDate();
var month = theDate.getMonth()+1; // js months are 0 based
var year = theDate.getFullYear();
var fd=today +'/'+ month +'/'+year
or perhaps you prefer 22/05/2011
var theDate = new Date();
var today = theDate.getDate();
if (today<10) today="0"+today;
var month = theDate.getMonth()+1; // js months are 0 based
if (month < 10) month = "0"+month;
var year = theDate.getFullYear();
var fd=""+today +"/"+ month +"/"+year
You are no longer adding 1 to the month, you are adding it to today. Make sure to parenthesize this since "x" + 1 + 2 => "x12" but "x" + (1 + 2) => "x3"