I'm taking a college course on JavaScript and am trying to follow one of the Chapter Hands-On Activites (using the textbook JavaScript: The Web Warrior Series By Sasha Vodnik and Don Gosselin in Chapter 7). It's supposed to create a calendar widget which isn't showing up. My end goal is to show the time elapsed from the date entered by the user.
This is the code provided in the textbook. I've copied it as exactly as is, double checked for errors, and used debugging tools. Google Chrome developer tools doesn't indicate any errors.
JS Code:
var dateObject = new Date();
function displayCalendar(whichMonth) {
var dateObject = new Date();
var date;
var dateToday = newDate();
var dayOfWeek;
var daysInMonth;
var dateCells;
var captionValue;
var month;
var year;
var monthArray = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "Decemeber"];
if (whichMonth === -1) {
dateObject.setMonth(dateObject.getMonth() - 1);
} else if (whichMonth === 1) {
dateObject.setMonth(dateObject.getMonth() + 1);
}
month = dateObject.getMonth();
year = dateObject.getFullYear();
dateObject.setDate(1);
dayOfWeek = dateObject.getDay();
captionValue = monthArray[month] + " " + year;
document.querySelector("#cal table caption").innerHTML = captionValue;
if(month === 0 || month === 2 || month === 4 || month === 6 || month === 7 || month === 9 || month === 11) { // Jan, Mar, May, Jul, Aug, Oct, Dec
daysInMonth = 31;
} else if (month === 1) { // Feb
if (year % 4 === 0) { //leap year test
if (year % 100 === 0) {
// year ending in 00 not a leap year unless
// divisible by 400
if (year % 400 === 0) {
daysInMonth = 29;
} else {
daysInMonth = 28;
}
} else {
daysInMonth = 29;
}
} else {
daysInMonth = 28;
}
} else { //Apr, Jun, Sep, Nov
daysInMonth = 30;
}
dateCells = document.getElementsByTagName("td");
for (var i = 0; i < dateCells.length; i++) {
// clear existing table dates
dateCells[i].innerHTML = "";
dateCells[i].className = "";
}
for (var i = dayOfWeek; i < daysInMonth + dayOfWeek; i++) {
// add dates to days cells
dateCells[i].innerHTML = dateObject.getDate();
dateCells[i].className = "date";
if (dateToday < dateObject) {
dateCells[i].className = "futuredate";
}
date = dateObject.getDate() + 1;
dateObject.setDate(date);
dateObject.setMonth(dateObject.getMonth() -1);
// reset month to month shown
document.getElementById("cal").style.display = "block";
// display calendar if it's not already visible
}
function selectDate(event) {
if (event === undefined) { //get caller element in IE8
event = window.event;
}
var callerElement = event.target || event.srcElement;
if (callerElement.innerHTML === "") {
//cell contains no date, so don't close the calendar
document.getElementById("cal").style.display = "block";
return false;
}
dateObject.setDate(callerElement.innerHTML);
var fullDateToday = new Date();
var dateToday = Date.UTC(fullDateToday.getFullYear(), fullDateToday.getMonth(), dateObject.getDate());
if (selectedDate <= dateToday) {
document.getElementById("cal").style.display = "block";
return false;
}
document.getElementById("tripDate").value = dateObject.toLocaleDateString();
}
function CreateEventListeners() {
var dateField = document.getElementById("tripDate");
if (dateField.addEventListener) {
dateField.addEventListener("click", displayCalendar, false);
} else if (dateField.attachEvent) {
dateField.attachEvent("onclick", displayCalendar);
}
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
} else if (window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}
var dateCells = document.getElementsByTagName("td");
if (dateCells[0].addEventListener) {
for (var i = 0; i < dateCells.length; i++) {
dateCells[i].addEventListener("click", selectDate, false);
}
} else if (dateCells[0].attachEvent) {
for (var i = 0; i < dateCells.length; i++) {
dateCells[i].attachEvent("onclick", selectDate);
}
}
}
Related
I'm trying to calculate duration when in the middle of date there is a holiday. I have tried when i choose the holiday date as the end date, the duration was 0. But if i choose next day the duration will calculate as usual without without a reduction in holidays. Whats must I add or change in my code
function getBusinessDatesCount(startDate, endDate) {
var count = 0;
var curDate = new Date(startDate);
var holiday = [];
holiday[0] = new Date('2019-08-08');
holiday[1] = new Date('2019-08-14');
while (curDate <= endDate) {
var dayOfWeek = curDate.getDay();
var isWeekend = (dayOfWeek == 6) || (dayOfWeek == 0);
if (!isWeekend && !isHoliday(endDate, holiday))
count++;
curDate.setDate(curDate.getDate() + 1);
}
function isHoliday(dt, arr) {
var bln = false;
for (var i = 0; i < arr.length; i++) {
if (compare(dt, arr[i])) { //If days are holidays
bln = true;
break;
}
}
return bln;
}
function compare(dt1, dt2) {
var equal = false;
if (dt1.getDate() == dt2.getDate() && dt1.getMonth() == dt2.getMonth() && dt1.getFullYear() == dt2.getFullYear()) {
equal = true;
}
return equal;
}
return count;
}
I expect when the date through the holiday, duration will not calculate the holiday date
I'm supposed to build a calendar with only html, css, and javascript - no php, no jquery, nothing. I have been working on a bug in my code all weekend, but I don't know where it comes from. I don't know what to do. This is my code:
"use strict";
window.onload = init;
function init() {
var day = new Date();
var month = day.getMonth() + 1;
var year = day.getYear() + 1900;
var next = document.getElementById("next");
var previous = document.getElementById("previous");
next.onclick = nextMonth(month);
previous.onclick = previousMonth(month);
generateCalendar(month, year);
}
function generateCalendar(_month, _year) {
var table = document.getElementById("calendar");
var month = ["Januar", "Februar", "März", "April", "Mai", "Juni",
"Juli", "August", "September", "Oktober", "November", "Dezember"];
var day = ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"];
var totaldays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
//determining the first day of the month
var firstday = new Date(_year, _month + 1, 1);
var start = firstday.getDay() + 1;
var end = totaldays[_month - 1]; //determining the length of the month
//February
if (end === totaldays[1]) {
//leap years (% means modulo)
if ((_year % 4 === 0 && _year % 100 !== 0) || _year % 400 === 0) {
end = 29;
}
}
//tale header
var head = month[_month - 1] + " " + _year;
var caption = table.createCaption();
caption.innerHTML = head;
var cell;
var row = table.insertRow(0);
for (var i = 0; i <= 6; i++) {
cell = row.insertCell(i);
cell.innerHTML = day[i];
}
var days = 1;
for (var i = 0; i <= 5; i++) { //started week in a month
row = table.insertRow(i + 1);
for (var j = 0; j <= 6; j++) { //days of a week
//regular calendar days
if (days <= end && (i > 0 || j >= start)) {
cell = row.insertCell(j);
cell.innerHTML = days;
days++;
} else {
//Days that aren't in the current month are shown as empty
cell = row.insertCell(j);
cell.innerHTML = "";
}
}
}
}
function nextMonth(_month) {
//contruction site
}
function previousMonth(_month) {
//construction site
}
My html file pretty much only has a <table> with the id named above.
So the calendar is in German obviously. As you can see (I hope) I tried to put the first day of the month on a field in an array from 0-6 for my week days which is very basic and it works!
Until December. The first day of December is supposed to be a Friday, but in my calendar it's on a Saturday and I have no idea why it jumps a day ahead. I debugged it and all I see is it skips a day in my array. I suppose it has something to do with the +1 at firstday.getDay() but I need that because all the Date functions are so inconsistent.
I'm going to create a calendar using moment.js, now I want to know how to get months and days for each month? I found this code but I didn't understand what it does:
function generateMonth() {
var weeks = [];
var done = false, date = moment().clone(), monthIndex = moment().month(), count = 0;
while (!done) {
weeks.push({ days: generateDays(moment().clone(), moment()) });
date.add(1, "w");
done = count++ > 2 && monthIndex !== date.month();
monthIndex = date.month();
}
}
function generateDays(date, month) {
var days = [];
for (var i = 0; i < 7; i++) {
days.push({
number: date.date(),
isCurrentMonth: date.month() === month.month(),
isToday: date.isSame(new Date(), "day")
});
date = date.clone();
date.add(1, "d");
}
return days;
}
In my Date Picker, you can select date and time. I am using Javascript. You can select date and time by clicking. After selecting date, you will land up to time page. After selecting a time from timeslots, date and time both will go to server. I want to highlight the selected date and time with red color, even after reload the page color should be there. Date must be highlighted with time as well. So, that if you come back then date color should be highlighted too. Main thing, I want to store the color somewhere, so if I reload the page then I should see the color. Here, is my date and time getting JS code and I have added plunker below.
datepicker = angular.module('datepicker', []);
datepicker.controller('dateTimePicker', ['$scope', '$http', 'formatDateTime', '$filter', function($scope, $http, formatDateTime, $filter) {
$scope.showType = 1;
$scope.selected = {};
$scope.changeShowType = function (type) {
$scope.showType = type;
$scope.monthName = $filter('date')($scope.selected.date, 'MMM yyyy');
};
$scope.selectDate = function(date) {
console.log(date);
$scope.showType = 2;
$scope.selected.date = date;
$scope.monthName = $filter('date')(date, 'dd MMM yyyy');
};
$scope.selectTime = function(time) {
$scope.selected.time = time;
$http.post('date/selected', $scope.selected);
};
var getTimeValues = function() {
formatDateTime.getTimeValues();
}
getTimeValues();
var bindScope = function() {
$scope.timeValues = formatDateTime.timeValues;
}
bindScope();
//Date Picker START
var date = new Date();
var months = [],
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var tempMonth;
tempMonth = date.getMonth();
for (var i = 0; i <= 12; i++) {
months.push(monthNames[tempMonth] + ' ' + date.getFullYear());
tempMonth += 1;
if (tempMonth >= 12) {
tempMonth = 0;
date.setFullYear(date.getFullYear() + 1);
}
}
$scope.year = 2015;
$scope.changeMonth = function(steps) {
if ($scope.monthIndex + steps >= 0 && $scope.monthIndex + steps <= 12) {
$scope.dateValues = [];
$scope.monthIndex = $scope.monthIndex + steps;
$scope.monthName = $scope.months[$scope.monthIndex];
var date = new Date();
console.log(date.getMonth());
var offset = date.getMonth()
console.log($scope.monthIndex);
var offsetDate = offset + $scope.monthIndex;
$scope.nDays = new Date($scope.year, offsetDate + 1, 0).getDate();
console.log(offsetDate + 1);
console.log(new Date($scope.year, offsetDate, 1));
for (i = 1; i <= $scope.nDays; i++) {
var d = new Date();
d.setHours(0, 0, 0, 0);
var displayDate = new Date($scope.year, offsetDate, i);
if (displayDate >= d) $scope.dateValues.push(displayDate);
}
} else {
console.log("missed")
}
$scope.showType =1;
};
$scope.monthIndex = 0;
$scope.months = months;
$scope.monthName = months[0];
$scope.changeMonth(0);
}]);
datepicker.factory('formatDateTime', [function() {
return {
//final structures which are bound to view
//
dateValues: [],
timeValues: [],
//generates one hour slots between minTime and maxTime
getTimeValues: function() {
console.log('here i am');
var timeValues = this.timeValues;
var minTime = 11; //vary this to change the first service slot available
var maxTime = 19; //vary this to chage the last service slot available
var string;
for (var i = minTime; i < maxTime; i++) {
if (i < 12) {
lowersuffix = 'AM';
startRange = i;
} else if (i === 12) {
lowersuffix = 'PM';
startRange = i;
} else {
lowersuffix = 'PM';
startRange = i - 12;
}
if ((i + 1) < 12) {
uppersuffix = 'AM';
endRange = (i + 1);
} else if ((i + 1) === 12) {
uppersuffix = 'PM';
endRange = (i + 1);
} else {
uppersuffix = 'PM';
endRange = (i + 1) - 12;
}
string = startRange + lowersuffix + '-' + endRange + uppersuffix;
console.log(string);
timeValues.push(string);
}
}
};
}]);
Plunker Link :- http://plnkr.co/edit/35UwiYLEqv3LYY6RiL1q?p=preview
you can use cookies to store the values
document.cookie="username=John Doe";
W3Schools Cookies
If your target browser supports localStorage I would recommend:
localStorage.setItem("colour", "blue");
localStorage.getItem("colour");
I have a function that works out the past 3 months and displays the name by using an array.
I've just realised that when the new year comes round, for January, February & March, it won't be able to get the correct month.
I want to be able to do this without having to add in a hack (which is the only way I've seen to do this)
function getMonths()
{
var today = new Date();
var month = 0;
var currMonth = month-3;
var monthArray = new Array("January","February","March","April","May","June",
"July","August","September","October","November","December");
var menuMonths = new Array();
var count = 4;
var buffer = 10;
while(count >0)
{
var month = monthArray[currMonth];
alert(currMonth);
menuMonths.push(month);
currMonth = currMonth +1;
count = count -1;
}
return menuMonths;
}
Modulus is your friend. Try:
function getMonths()
{
var today = new Date();
var month = 1;
var monthArray = new Array("January","February","March","April","May","June",
"July","August","September","October","November","December");
var menuMonths = new Array();
for(var count = 3; count >= 0; count--)
menuMonths.push(monthArray[((12 + month - count) % 12)]);
return menuMonths;
}
alert(getMonths());
This little addition to your while-loop will ensure that currMonth is always a valid index of your monthArray:
while(count >0)
{
if (currMonth < 0)
currMonth += 12;
if (currMonth >=12 )
currMonth -= 12;
var month = monthArray[currMonth];
menuMonths.push(month);
currMonth = currMonth +1;
count = count -1;
}
working example: http://jsfiddle.net/RWhN4/
This is a bit hackish, but it should do what you want.
To figure out which month was 3 months ago you could do the following:
var d = new Date();
d.setMonth(d.getMonth() - 3);
var monthIndex = d.getMonth() //(0-11)
Let standard javascript methods do the calculations for you.
Here is your function updated to use the javascript methods to do the calculations for you:
function getMonths() {
var date = new Date();
//subttract 3 months
date.setMonth(0 - 3);
var monthArray = new Array("January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December");
var menuMonths = new Array();
var count = 4;
var buffer = 10;
while (count > 0) {
var month = monthArray[date.getMonth()];
alert(month);
menuMonths.push(month);
date.setMonth(date.getMonth() + 1);
count -= 1;
}
return menuMonths;
}
I did something similar to what you guys did, but I did it for the Trailing Twelve Months basically, in it's form format I used the following code:
$(".monthly_usage").val('');
var monthArray = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var today = new Date();
var month = today.getMonth();
var year = today.getFullYear();
var output = "Enter Trailing Twelve Months Usage<br/><center><table border=1 cellpadding=10 cellspacing=0><thead><th>Month - Year</th><th>Usage</th></thead><tbody>";
for(var i = 0; i < 12; i++) {
output += "<tr><td>" + monthArray[today.getMonth()] + " " + year + "</td><td><input type=text class=monthly_usage name=usage[]></td></tr>";
var month = today.setMonth(today.getMonth() - 1);
var year = today.getFullYear();
}
output += "</tbody></table>"+
"<button id=submit_ttm>Submit Monthly Usage</button></center>";
return output;
function lastMonths(count,month,order) {
var arr = [];
//defaults
month = typeof month !== 'undefined' ? month : new Date().getMonth();
count = typeof count !== 'undefined' ? count : 3;
order = typeof order !== 'undefined' ? order : "asc";
while (count-- > 0) {
month = (--month < 0) ? 11 : month;
arr.push(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][month]);
}
return ( order === "asc" ) ? arr.reverse() : arr;
}
the function has defaults for the number of months to show, the start month, and the order
demo