I am trying to display a two week view using Calenderio. So for example it should display 4/19/2015 - 5/2/2015, not the entire month of April. I am confused as to where in the JS I have to modify it to display only two weeks.
Here is the JS:
function($, window, undefined) {
'use strict';
$.Calendario = function(options, element) {
this.$el = $(element);
this._init(options);
};
// the options
$.Calendario.defaults = {
/*
you can also pass:
month : initialize calendar with this month (1-12). Default is today.
year : initialize calendar with this year. Default is today.
caldata : initial data/content for the calendar.
caldata format:
{
'MM-DD-YYYY' : 'HTML Content',
'MM-DD-YYYY' : 'HTML Content',
...
}
*/
weeks: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
weekabbrs: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
monthabbrs: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
displayWeekAbbr: false, // choose between values in options.weeks or options.weekabbrs
displayMonthAbbr: false, // choose between values in options.months or options.monthabbrs
startIn: 0, // left most day in the calendar (0 - Sunday, 1 - Monday, ... , 6 - Saturday)
events: 'click',
fillEmpty: true,
feedParser: './feed/',
zone: '00:00', // Ex: IST zone time is '+05:30' by default it is GMT, Sign is important.
checkUpdate: true //Check if any new version of Calendario is released (Details will be in the browser console)
};
$.Calendario.prototype = {
_init: function(options) {
// options
this.VERSION = '3.2.0';
this.UNIQUE = '%{unique}%'; //UNIQUE helps us differentiate your js from others and help us keep a track of run time.
this.options = $.extend(true, {}, $.Calendario.defaults, options);
this.today = new Date();
this.month = (isNaN(this.options.month) || this.options.month === null) ? this.today.getMonth() : this.options.month - 1;
this.year = (isNaN(this.options.year) || this.options.year === null) ? this.today.getFullYear() : this.options.year;
this.caldata = this._processCaldata(this.options.caldata);
// if hover is passed as an event then throw error if jQuery is 1.9 or above 1.9, because, hover psuedo name isn't supported
if (parseFloat($().jquery) >= 1.9 && this.options.events.indexOf('hover') != -1)
this.logError('\'hover\' psuedo-name is not supported' + ' in jQuery 1.9+. Use \'mouseenter\' \'mouseleave\' events instead.');
this.options.events = this.options.events.split(',');
this.options.zone = this.options.zone.charAt(0) != '+' && this.options.zone.charAt(0) != '-' ? '+' + this.options.zone : this.options.zone;
this._generateTemplate(true);
this._initEvents();
},
_processCaldataObj: function(val, key) {
if (typeof val !== 'object') val = {
content: val,
startTime: '00:00',
endTime: '23:59',
allDay: true
};
if (!val.content) this.logError('Content is missing in date ' + key);
if (val.startTime && !val.endTime) val.endTime = parseInt(val.startTime.split(':')[0]) + 1 + ':' + val.startTime.split(':')[1];
if (!val.startTime && !val.endTime) val = $.extend({}, val, {
startTime: '00:00',
endTime: '23:59',
allDay: true
});
if (val.startTime && val.endTime && val.allDay === undefined) val.allDay = false;
if (/^\d{2}-DD-\d{4}/.test(key) || /^\d{2}-DD-YYYY/.test(key)) {
var det = /^(\d{2})-DD-(\d{4})/.exec(key) || /^(\d{2})-DD-YYYY/.exec(key),
chkDate;
if (det.length == 3) chkDate = new Date(det[2], det[1], 0);
else if (det.length == 2) chkDate = new Date(this.year, det[1], 0)
if (!val.startDate) val.startDate = 1;
if (!val.endDate && chkDate.getDate() != 1) val.endDate = chkDate.getDate();
if (!val.endDate && chkDate.getDate() == 1 && det.length == 3) val.endDate = chkDate.getDate();
}
return val;
},
_processCaldata: function(caldata) {
var self = this;
caldata = caldata || {};
$.each(caldata, function(key, val) {
if (/^\d{2}-\d{2}-\d{4}/.test(key) || /^\d{2}-\d{2}-YYYY/.test(key) || /^\d{2}-DD-YYYY/.test(key) || /^MM-\d{2}-YYYY/.test(key) ||
/^\d{2}-DD-YYYY/.test(key) || /^MM-\d{2}-\d{4}/.test(key) || /^\d{2}-DD-\d{4}/.test(key) || key == 'TODAY') {} else
self.logError(key + ' is an Invalid Date. Date should not contain spaces, should be separated by \'-\' and should be in the ' +
'format \'MM-DD-YYYY\'. That ain\'t that difficult!');
if (Array.isArray(val)) {
$.each(val, function(i, c) {
val[i] = self._processCaldataObj(c, key);
});
caldata[key] = val;
} else {
caldata[key] = self._processCaldataObj(val, key);
}
});
return caldata;
},
_propDate: function($cell, event) {
var idx = $cell.index(),
data = {
allDay: [],
content: [],
endTime: [],
startTime: []
},
dateProp = {
day: $cell.children('span.fc-date').text(),
month: this.month + 1,
monthname: this.options.displayMonthAbbr ? this.options.monthabbrs[this.month] : this.options.months[this.month],
year: this.year,
weekday: idx + this.options.startIn,
weekdayname: this.options.weeks[(idx == 6 ? 0 : idx + this.options.startIn)]
};
$cell.children('div.fc-calendar-events').children('div.fc-calendar-event').each(function(i, e) {
var $html = $('<div>' + $(e).html() + '</div>');
data.startTime[i] = new Date($html.find('time.fc-starttime').attr('datetime'));
data.endTime[i] = new Date($html.find('time.fc-endtime').attr('datetime'));
data.allDay[i] = $html.find('time.fc-allday').attr('datetime') === 'true' ? true : false;
$html.find('time').remove();
data.content[i] = $html.html();
});
if (dateProp.day) this.options[event]($cell, data, dateProp);
},
_initEvents: function() {
var self = this,
event = [],
calendarioEventNameFormat = [];
for (var i = 0; i < self.options.events.length; i++) {
event[i] = self.options.events[i].toLowerCase().trim();
calendarioEventNameFormat[i] = 'onDay' + event[i].charAt(0).toUpperCase() + event[i].slice(1);
if (this.options[calendarioEventNameFormat[i]] === undefined)
this.options[calendarioEventNameFormat[i]] = function($el, $content, dateProperties) {
return false;
};
this.$el.on(event[i] + '.calendario', 'div.fc-row > div', function(e) {
if (e.type == 'mouseenter' || e.type == 'mouseleave') e.type = $.inArray(e.type, event) == -1 ? 'hover' : e.type;
self._propDate($(this), calendarioEventNameFormat[$.inArray(e.type, event)]);
});
}
this.$el.on('shown.calendar.calendario', function(e, instance) {
// If check update set to true, then contact calendario's update servers for details. We didn't want to slow down your code. So we
// check after the calendar is rendered.
if (instance && instance.options.checkUpdate) self._checkUpdate();
});
// newday trigger. This trigger is exactly triggered at 00:00 hours the next day with an uncertainty of 6ms.
this.$el.delay(new Date(this.today.getFullYear(), this.today.getMonth(), this.today.getDate() + 1, 0, 0, 0) - new Date().getTime())
.queue(function() {
self.today = new Date();
if (self.today.getMonth() == self.month || self.today.getMonth() + 1 == self.month) self._generateTemplate(true);
self.$el.trigger($.Event('newday.calendar.calendario'));
});
},
_checkUpdate: function() {
var self = this;
$.getScript("https://raw.githubusercontent.com/codrops/Calendario/master/js/update.js")
.done(function(script, textStatus) {
if (calendario.current != self.version() && parseFloat(calendario.current) >= parseFloat(self.version()))
console.info(calendario.msg);
})
.fail(function(jqxhr, settings, exception) {
console.error(exception);
});
},
// Calendar logic based on http://jszen.blogspot.pt/2007/03/how-to-build-simple-calendar-with.html
_generateTemplate: function(firstRun, callback) {
var head = this._getHead(),
body = this._getBody(),
rowClass;
switch (this.rowTotal) {
case 2:
rowClass = 'fc-two-rows';
break;
case 3:
rowClass = 'fc-three-rows';
break;
case 4:
rowClass = 'fc-four-rows';
break;
case 5:
rowClass = 'fc-five-rows';
break;
case 6:
rowClass = 'fc-six-rows';
break;
}
this.$cal = $('<div class="fc-calendar ' + rowClass + '">').append(head, body);
this.$el.find('div.fc-calendar').remove().end().append(this.$cal);
this.$el.find('.fc-emptydate').parent().css({
'background': 'transparent',
'cursor': 'default'
});
if (!firstRun) this.$el.trigger($.Event('shown.calendario'));
if (callback) callback.call();
},
_getHead: function() {
var html = '<div class="fc-head">';
for (var i = 0; i <= 6; i++) {
var pos = i + this.options.startIn,
j = pos > 6 ? pos - 6 - 1 : pos;
html += '<div>' + (this.options.displayWeekAbbr ? this.options.weekabbrs[j] : this.options.weeks[j]) + '</div>';
}
return html + '</div>';
},
_parseDataToDay: function(data, day, other) {
var content = '';
if (!other) {
if (Array.isArray(data)) content = this._convertDayArray(data, day);
else content = this._wrapDay(data, day, true);
} else {
if (!Array.isArray(data)) data = [data];
for (var i = 0; i < data.length; i++) {
if (this.month != 1 && (day >= data[i].startDate) && (day <= data[i].endDate)) content += this._wrapDay(data[i], day, true);
else if (this.month == 1 && (day >= data[i].startDate)) {
if (data[i].endDate && (day <= data[i].endDate)) content += this._wrapDay(data[i], day, true);
else if (!data[i].endDate) content += this._wrapDay(data[i], day, true);
}
}
}
return content;
},
_toDateTime: function(time, day, start) {
var zoneH = parseInt(this.options.zone.split(':')[0]),
zoneM = parseInt(this.options.zone.charAt(0) + this.options.zone.split(':')[1]),
hour = parseInt(time.split(':')[0]) - zoneH,
minutes = parseInt(time.split(':')[1]) - zoneM,
d = new Date(Date.UTC(this.year, this.month, day, hour, minutes, 0, 0));
if (start) {
var hStart = parseInt(start.split(':')[0]) - zoneH,
mStart = parseInt(start.split(':')[1]) - zoneM;
if (d.getTime() - new Date(Date.UTC(this.year, this.month, day, hStart, mStart, 0, 0)).getTime() < 0)
d = new Date(Date.UTC(this.year, this.month, day + 1, hour, minutes, 0, 0));
}
return d.toISOString();
},
_timeHtml: function(day, date) {
var content = day.content;
content += '<time class="fc-allday" datetime="' + day.allDay + '"></time>';
content += '<time class="fc-starttime" datetime="' + this._toDateTime(day.startTime, date) + '">' + day.startTime + '</time>';
content += '<time class="fc-endtime" datetime="' + this._toDateTime(day.endTime, date, day.startTime) + '">' + day.endTime + '</time>';
return content;
},
_wrapDay: function(day, date, wrap) {
if (date) {
if (wrap) return '<div class="fc-calendar-event">' + this._timeHtml(day, date) + '</div>';
else return this._timeHtml(day, date);
} else return '<div class="fc-calendar-event">' + day + '</div>';
},
_convertDayArray: function(day, date) {
var wrap_days = []
for (var i = 0; i < day.length; i++) {
wrap_days[i] = this._wrapDay(day[i], date, false);
}
return this._wrapDay(wrap_days.join('</div><div class="fc-calendar-event">'));
},
_getBody: function() {
var d = new Date(this.year, this.month + 1, 0),
monthLength = d.getDate(), // number of days in the month
firstDay = new Date(this.year, d.getMonth(), 1),
pMonthLength = new Date(this.year, this.month, 0).getDate();
// day of the week
this.startingDay = firstDay.getDay();
var html = '<div class="fc-body"><div class="fc-row">',
day = 1; // fill in the days
for (var i = 0; i < 7; i++) { // this loop is for weeks (rows)
for (var j = 0; j <= 6; j++) { // this loop is for weekdays (cells)
var pos = this.startingDay - this.options.startIn,
p = pos < 0 ? 6 + pos + 1 : pos,
inner = '',
today = this.month === this.today.getMonth() && this.year === this.today.getFullYear() && day === this.today.getDate(),
past = this.year < this.today.getFullYear() || this.month < this.today.getMonth() && this.year === this.today.getFullYear() ||
this.month === this.today.getMonth() && this.year === this.today.getFullYear() && day < this.today.getDate(),
content = '';
if (this.options.fillEmpty && (j < p || i > 0)) {
if (day > monthLength) {
inner = '<span class="fc-date fc-emptydate">' + (day - monthLength) + '</span><span class="fc-weekday">';
++day;
} else if (day == 1) {
inner = '<span class="fc-date fc-emptydate">' + (pMonthLength - p + 1) + '</span><span class="fc-weekday">';
++pMonthLength;
}
inner += this.options.weekabbrs[j + this.options.startIn > 6 ? j + this.options.startIn - 6 - 1 : j + this.options.startIn] + '</span>';
}
if (day <= monthLength && (i > 0 || j >= p)) {
inner = '<span class="fc-date">' + day + '</span><span class="fc-weekday">' + this.options.weekabbrs[j +
this.options.startIn > 6 ? j + this.options.startIn - 6 - 1 : j + this.options.startIn] + '</span>';
var strdate = (this.month + 1 < 10 ? '0' + (this.month + 1) : this.month + 1) + '-' + (day < 10 ? '0' + day : day) + '-' + this.year,
dayData = this.caldata[strdate],
strdateyear = (this.month + 1 < 10 ? '0' + (this.month + 1) : this.month + 1) + '-' + (day < 10 ? '0' + day : day) + '-YYYY',
dayDataYear = this.caldata[strdateyear],
strdatemonth = 'MM-' + (day < 10 ? '0' + day : day) + '-' + this.year,
dayDataMonth = this.caldata[strdatemonth],
strdatemonthyear = 'MM' + '-' + (day < 10 ? '0' + day : day) + '-YYYY',
dayDataMonthYear = this.caldata[strdatemonthyear],
strdatemonthlyyear = (this.month + 1 < 10 ? '0' + (this.month + 1) : this.month + 1) + '-DD-' + this.year,
dayDataMonthlyYear = this.caldata[strdatemonthlyyear],
strdatemonthly = (this.month + 1 < 10 ? '0' + (this.month + 1) : this.month + 1) + '-DD-YYYY',
dayDataMonthly = this.caldata[strdatemonthly];
if (today && this.caldata.TODAY) content += this._parseDataToDay(this.caldata.TODAY, day);
if (dayData) content += this._parseDataToDay(dayData, day);
if (dayDataMonth) content += this._parseDataToDay(dayDataMonth, day);
if (dayDataMonthlyYear) content += this._parseDataToDay(dayDataMonthlyYear, day, true);
if (dayDataMonthly) content += this._parseDataToDay(dayDataMonthly, day, true);
if (dayDataMonthYear) content += this._parseDataToDay(dayDataMonthYear, day);
if (dayDataYear) content += this._parseDataToDay(dayDataYear, day);
if (content !== '') inner += '<div class="fc-calendar-events">' + content + '</div>';
++day;
} else {
today = false;
}
var cellClasses = today ? 'fc-today ' : '';
if (past) cellClasses += 'fc-past ';
else cellClasses += 'fc-future ';
if (content !== '') cellClasses += 'fc-content';
html += (cellClasses !== '' ? '<div class="' + cellClasses.trim() + '">' : '<div>') + inner + '</div>';
}
if (day > monthLength) { // stop making rows if we've run out of days
this.rowTotal = i + 1;
break;
} else {
html += '</div><div class="fc-row">';
}
}
return html + '</div></div>';
},
_move: function(period, dir, callback) {
if (dir === 'previous') {
if (period === 'month') {
this.year = this.month > 0 ? this.year : --this.year;
this.month = this.month > 0 ? --this.month : 11;
} else if (period === 'year') this.year = --this.year;
} else if (dir === 'next') {
if (period === 'month') {
this.year = this.month < 11 ? this.year : ++this.year;
this.month = this.month < 11 ? ++this.month : 0;
} else if (period === 'year') this.year = ++this.year;
}
this._generateTemplate(false, callback);
},
/*************************
***** PUBLIC METHODS *****
**************************/
option: function(option, value) {
if (value) this.options[option] = value;
else return this.options[option];
},
getYear: function() {
return this.year;
},
getMonth: function() {
return this.month + 1;
},
getMonthName: function() {
return this.options.displayMonthAbbr ? this.options.monthabbrs[this.month] : this.options.months[this.month];
},
// gets the cell's content div associated to a day of the current displayed month
// day : 1 - [28||29||30||31]
getCell: function(day) {
var row = Math.floor((day + this.startingDay - this.options.startIn - 1) / 7),
pos = day + this.startingDay - this.options.startIn - (row * 7) - 1;
return this.$cal.find('div.fc-body').children('div.fc-row').eq(row).children('div').eq(pos);
},
setData: function(caldata, clear) {
caldata = this._processCaldata(caldata);
if (clear) this.caldata = caldata;
else $.extend(this.caldata, caldata);
this._generateTemplate(false);
},
// goes to today's month/year
gotoNow: function(callback) {
this.month = this.today.getMonth();
this.year = this.today.getFullYear();
this._generateTemplate(false, callback);
},
// goes to month/year
gotoMonth: function(month, year, callback) {
this.month = month - 1;
this.year = year;
this._generateTemplate(false, callback);
},
gotoPreviousMonth: function(callback) {
this._move('month', 'previous', callback);
},
gotoPreviousYear: function(callback) {
this._move('year', 'previous', callback);
},
gotoNextMonth: function(callback) {
this._move('month', 'next', callback);
},
gotoNextYear: function(callback) {
this._move('year', 'next', callback);
},
feed: function(callback) {
var self = this;
$.post(self.options.feedParser, {
dates: this.caldata
})
.always(function(data) {
if (callback) callback.call(this, JSON.parse(data).hevent);
});
},
version: function() {
return this.VERSION;
}
};
var logError = function(message) {
throw new Error(message);
};
$.fn.calendario = function(options) {
var instance = $.data(this, 'calendario');
if (typeof options === 'string') {
var args = Array.prototype.slice.call(arguments, 1);
this.each(function() {
if (!instance) {
logError("Cannot call methods on calendario prior to initialization; Attempted to call method '" + options + "'");
return;
}
if (!$.isFunction(instance[options]) || options.charAt(0) === "_") {
logError("No such method '" + options + "' for calendario instance.");
}
instance[options].apply(instance, args);
});
} else {
this.each(function() {
if (instance) instance._init();
else instance = $.data(this, 'calendario', new $.Calendario(options, this));
});
}
instance.$el.trigger($.Event('shown.calendar.calendario'), [instance]);
return instance;
};
})(jQuery, window);
I'm not sure you can yet - Developer of the version you posted, better version available at https://github.com/deviprsd21/Calendario
Related
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
I wrote the following code for displaying a different image depending on the date (right now this example just console logs a message). The code works fine in Chrome and Firefox on Mac, but does not work correctly or give any errors on Safari (in Safari the message does not change depending on the date, it just says the same). How is Safari processing this differently? How can I get this to work on Safari with minimal changes?
Here's a working repl.
Here's the code:
/* change these dates */
var ddt = new Date("2019, 8, 22");
var pre = new Date("2019, 8, 23");
var ton = new Date("2019, 8, 26");
var post = new Date("2019, 8, 27");
// todays date
var currDate = new Date();
var mm = currDate.getMonth() + 1;
var dd = currDate.getDate();
var yyyy = currDate.getFullYear();
// Get the date parts
var ddtDay = ddt.getDate();
var ddtMonth = ddt.getMonth() + 1;
var ddtYear = ddt.getFullYear();
//console.log(ddtYear, ddtMonth, ddtDay);
var preDay = pre.getDate();
var preMonth = pre.getMonth() + 1;
var preYear = pre.getFullYear();
//console.log(preYear, preMonth, preDay);
var tonDay = ton.getDate();
var tonMonth = ton.getMonth() + 1;
var tonYear = ton.getFullYear();
//console.log(tonYear, tonMonth, tonDay);
var postDay = post.getDate();
var postMonth = post.getMonth() + 1;
var postYear = post.getFullYear();
//console.log(postYear, postMonth, postDay);
// format the date parts
if (ddtDay < 10) {
ddtDay = '0' + ddtDay;
}
if (ddtMonth < 10) {
ddtMonth = '0' + ddtMonth;
}
if (preDay < 10) {
preDay = '0' + preDay;
}
if (preMonth < 10) {
preMonth = '0' + preMonth;
}
if (tonDay < 10) {
tonDay = '0' + tonDay;
}
if (tonMonth < 10) {
tonMonth = '0' + tonMonth;
}
if (postDay < 10) {
postDay = '0' + postDay;
}
if (tonMonth < 10) {
postMonth = '0' + postMonth;
}
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var ddtF = (ddtYear + '-' + ddtMonth + '-' + ddtDay);
var preF = (preYear + '-' + preMonth + '-' + preDay);
var tonF = (tonYear + '-' + tonMonth + '-' + tonDay);
var postF = (postYear + '-' + postMonth + '-' + postDay);
var today = (yyyy + '-' + mm + '-' + dd);
console.log(ddtF);
console.log(preF);
console.log(tonF);
console.log(postF);
console.log(today);
// logic
if (today >= postF) {
console.log('post');
} else if (today === tonF) {
console.log('ton');
} else if (today < tonF && today >= preF) {
console.log('pre');
} else if (today <= ddtF) {
console.log('ddt');
}
"2019, 8, 22" is not a portable date format. The Date constructor has a portable calling sequence where you give each component of the date as a separate argument, so use
var ddt = new Date(2019, 7, 22);
and similarly for all the other variables.
And remember that months are counted from 0 in JavaScript, so you need to subtract 1 from the month argument (August is 7).
/* change these dates */
var ddt = new Date(2019, 7, 22);
var pre = new Date(2019, 7, 23);
var ton = new Date(2019, 7, 26);
var post = new Date(2019, 7, 27);
// todays date
var currDate = new Date();
var mm = currDate.getMonth() + 1;
var dd = currDate.getDate();
var yyyy = currDate.getFullYear();
// Get the date parts
var ddtDay = ddt.getDate();
var ddtMonth = ddt.getMonth() + 1;
var ddtYear = ddt.getFullYear();
//console.log(ddtYear, ddtMonth, ddtDay);
var preDay = pre.getDate();
var preMonth = pre.getMonth() + 1;
var preYear = pre.getFullYear();
//console.log(preYear, preMonth, preDay);
var tonDay = ton.getDate();
var tonMonth = ton.getMonth() + 1;
var tonYear = ton.getFullYear();
//console.log(tonYear, tonMonth, tonDay);
var postDay = post.getDate();
var postMonth = post.getMonth() + 1;
var postYear = post.getFullYear();
//console.log(postYear, postMonth, postDay);
// format the date parts
if (ddtDay < 10) {
ddtDay = '0' + ddtDay;
}
if (ddtMonth < 10) {
ddtMonth = '0' + ddtMonth;
}
if (preDay < 10) {
preDay = '0' + preDay;
}
if (preMonth < 10) {
preMonth = '0' + preMonth;
}
if (tonDay < 10) {
tonDay = '0' + tonDay;
}
if (tonMonth < 10) {
tonMonth = '0' + tonMonth;
}
if (postDay < 10) {
postDay = '0' + postDay;
}
if (tonMonth < 10) {
postMonth = '0' + postMonth;
}
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var ddtF = (ddtYear + '-' + ddtMonth + '-' + ddtDay);
var preF = (preYear + '-' + preMonth + '-' + preDay);
var tonF = (tonYear + '-' + tonMonth + '-' + tonDay);
var postF = (postYear + '-' + postMonth + '-' + postDay);
var today = (yyyy + '-' + mm + '-' + dd);
console.log(ddtF);
console.log(preF);
console.log(tonF);
console.log(postF);
console.log(today);
// logic
if (today >= postF) {
console.log('post');
} else if (today === tonF) {
console.log('ton');
} else if (today < tonF && today >= preF) {
console.log('pre');
} else if (today <= ddtF) {
console.log('ddt');
}
I'm using the following jQuery date range picker library : http://longbill.github.io/jquery-date-range-picker/
I would like to remove / hide all Sundays from all date range pickers while keeping a normal behavior on the date range pickers.
I tried to do something with beforeShowDay option :
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = '';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
but it only "disables" all Sundays whereas I want to remove / hide them:
Here's the fiddle I'm working on : https://jsfiddle.net/maximelafarie/dnbd01do/11/
EDIT:
Updated fiddle with #Swanand code: https://jsfiddle.net/maximelafarie/dnbd01do/18/
You could do it with just a little CSS but it does leave a gap:
.week-name th:nth-child(7),
.month1 tbody tr td:nth-child(7) {
display: none;
}
Hope this helps a little.
You need do changes in two functions in your daterangepicker.js file:
createMonthHTML()
function createMonthHTML(d) { var days = [];
d.setDate(1);
var lastMonth = new Date(d.getTime() - 86400000);
var now = new Date();
var dayOfWeek = d.getDay();
if ((dayOfWeek === 0) && (opt.startOfWeek === 'monday')) {
// add one week
dayOfWeek = 7;
}
var today, valid;
if (dayOfWeek > 0) {
for (var i = dayOfWeek; i > 0; i--) {
var day = new Date(d.getTime() - 86400000 * i);
valid = isValidTime(day.getTime());
if (opt.startDate && compare_day(day, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(day, opt.endDate) > 0) valid = false;
days.push({
date: day,
type: 'lastMonth',
day: day.getDate(),
time: day.getTime(),
valid: valid
});
}
}
var toMonth = d.getMonth();
for (var i = 0; i < 40; i++) {
today = moment(d).add(i, 'days').toDate();
valid = isValidTime(today.getTime());
if (opt.startDate && compare_day(today, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(today, opt.endDate) > 0) valid = false;
days.push({
date: today,
type: today.getMonth() == toMonth ? 'toMonth' : 'nextMonth',
day: today.getDate(),
time: today.getTime(),
valid: valid
});
}
var html = [];
for (var week = 0; week < 6; week++) {
if (days[week * 7].type == 'nextMonth') break;
html.push('<tr>');
for (var day = 0; day < 7; day++) {
var _day = (opt.startOfWeek == 'monday') ? day + 1 : day;
today = days[week * 7 + _day];
var highlightToday = moment(today.time).format('L') == moment(now).format('L');
today.extraClass = '';
today.tooltip = '';
if (today.valid && opt.beforeShowDay && typeof opt.beforeShowDay == 'function') {
var _r = opt.beforeShowDay(moment(today.time).toDate());
today.valid = _r[0];
today.extraClass = _r[1] || '';
today.tooltip = _r[2] || '';
if (today.tooltip !== '') today.extraClass += ' has-tooltip ';
}
var todayDivAttr = {
time: today.time,
'data-tooltip': today.tooltip,
'class': 'day ' + today.type + ' ' + today.extraClass + ' ' + (today.valid ? 'valid' : 'invalid') + ' ' + (highlightToday ? 'real-today' : '')
};
if (day === 0 && opt.showWeekNumbers) {
html.push('<td><div class="week-number" data-start-time="' + today.time + '">' + opt.getWeekNumber(today.date) + '</div></td>');
}
if(day == 0){
html.push('<td class="hideSunday"' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}else{
html.push('<td ' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}
}
html.push('</tr>');
}
return html.join('');
}
In this function i have added class hideSunday while pushing the element.
The 2nd function is getWeekHead():
function getWeekHead() {
var prepend = opt.showWeekNumbers ? '<th>' + translate('week-number') + '</th>' : '';
if (opt.startOfWeek == 'monday') {
return prepend + '<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>' +
'<th class="hideSunday">' + translate('week-7') + '</th>';
} else {
return prepend + '<th class="hideSunday">' + translate('week-7') + '</th>' +
'<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>';
}
}
In this file, I have added class to week-7 header.
CSS:
.hideSunday{display:none;}
Please note, I have not checked all the scenario but it will do trick for you.
I finally ended up by letting the Sundays appear (but completely disabling them).
These questions inspired me :
Moment.js - Get all mondays between a date range
Moment.js: Date between dates
So I created a function as follows which returns an array that contains the "sundays" (or whatever day you provide as dayNumber parameter) in the date range you selected:
function getDayInRange(dayNumber, startDate, endDate, inclusiveNextDay) {
var start = moment(startDate),
end = moment(endDate),
arr = [];
// Get "next" given day where 1 is monday and 7 is sunday
let tmp = start.clone().day(dayNumber);
if (!!inclusiveNextDay && tmp.isAfter(start, 'd')) {
arr.push(tmp.format('YYYY-MM-DD'));
}
while (tmp.isBefore(end)) {
tmp.add(7, 'days');
arr.push(tmp.format('YYYY-MM-DD'));
}
// If last day matches the given dayNumber, add it.
if (end.isoWeekday() === dayNumber) {
arr.push(end.format('YYYY-MM-DD'));
}
return arr;
}
Then I call this function in my code like that:
$('#daterange-2')
.dateRangePicker(configObject2)
.bind('datepicker-change', function(event, obj) {
var sundays = getDayInRange(7, moment(obj.date1), moment(obj.date1).add(selectedDatesCount, 'd'));
console.log(sundays);
$('#daterange-2')
.data('dateRangePicker')
.setDateRange(obj.value, moment(obj.date1)
.add(selectedDatesCount + sundays.length, 'd')
.format('YYYY-MM-DD'), true);
});
This way, I retrieve the amount of sundays in the date range I selected. For example, if there's two sundays in my selection (with sundays.length), I know I have to set two additional workdays to the user selection (in the second date range picker).
Here's the working result:
With the above screenshot, you can see the user selected 4 workdays (5 with sunday but we don't count it). Then he click on the second calendar and the 4 workdays automatically apply.
Here's the result if the period apply over a sunday (we add one supplementary day and Xfor X sundays in the period):
Finally, here's the working fiddle: https://jsfiddle.net/maximelafarie/dnbd01do/21/
I want to thank any person that helped me. The question was hard to explain and to understand.
You can also do it by setting a custom css class and use it in beforeShowDay like below
.hideSunDay{
display:none;
}
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = t.getDay() !== 0 ? '' : 'hideSunDay';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
But it only hides the sundays beginning from current day.
Here is a working fiddle
https://jsfiddle.net/dnbd01do/16/
I have a HMTL which execute a external JS. The JS returns my Google Calender events. I want my calender to be updated automatically every 10minutes.
The HTML looks like:
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="format-google-calendar.js"></script>
<script>
formatGoogleCalendar.init({
calendarUrl: 'https://www.googleapis.com/calendar/v3/calendars/magic.kfs#gmx.de/events?key=AIzaSyDei0zrhHPHAtYc5x7vjdUmGaC3FlFnm1Y ',
past: true,
upcoming: true,
sameDayTimes: true,
pastTopN: 20,
upcomingTopN: 4,
recurringEvents: true,
itemsTagName: 'ul',
upcomingSelector: '#events-upcoming',
pastSelector: '#events-past',
upcomingHeading: '<div id="Termine" >Kommende Termine</div> ',
pastHeading: '<p><h2 class="medium left">Vergangene Termine</h2></p>',
format: ['*date*', ': ', '*summary*', ' — ', '*description*', ' in ', '*location*']
});
</script>
The JS looks like:
var formatGoogleCalendar = (function() {
'use strict';
var config;
//Gets JSON from Google Calendar and transfroms it into html list items and appends it to past or upcoming events list
var init = function(settings) {
var result = [];
config = settings;
var finalURL = settings.calendarUrl;
if(settings.recurringEvents) finalURL = finalURL.concat("&singleEvents=true");
//Get JSON, parse it, transform into list items and append it to past or upcoming events list
jQuery.getJSON(finalURL, function(data) {
// Remove any cancelled events
data.items.forEach(function removeCancelledEvents(item) {
if (item && item.hasOwnProperty('status') && item.status !== 'cancelled') {
result.push(item);
}
});
result.sort(comp).reverse();
var pastCounter = 0,
upcomingCounter = 0,
pastResult = [],
upcomingResult = [],
upcomingResultTemp = [],
$upcomingElem = jQuery(settings.upcomingSelector),
$pastElem = jQuery(settings.pastSelector),
i;
if (settings.pastTopN === -1) {
settings.pastTopN = result.length;
}
if (settings.upcomingTopN === -1) {
settings.upcomingTopN = result.length;
}
if (settings.past === false) {
settings.pastTopN = 0;
}
if (settings.upcoming === false) {
settings.upcomingTopN = 0;
}
for (i in result) {
if (isPast(result[i].end.dateTime || result[i].end.date)) {
if (pastCounter < settings.pastTopN) {
pastResult.push(result[i]);
pastCounter++;
}
} else {
upcomingResultTemp.push(result[i]);
}
}
upcomingResultTemp.reverse();
for (i in upcomingResultTemp) {
if (upcomingCounter < settings.upcomingTopN) {
upcomingResult.push(upcomingResultTemp[i]);
upcomingCounter++;
}
}
for (i in pastResult) {
$pastElem.append(transformationList(pastResult[i], settings.itemsTagName, settings.format));
}
for (i in upcomingResult) {
$upcomingElem.append(transformationList(upcomingResult[i], settings.itemsTagName, settings.format));
}
if ($upcomingElem.children().length !== 0) {
jQuery(settings.upcomingHeading).insertBefore($upcomingElem);
}
if ($pastElem.children().length !== 0) {
jQuery(settings.pastHeading).insertBefore($pastElem);
}
});
};
//Compare dates
var comp = function(a, b) {
return new Date(a.start.dateTime || a.start.date).getTime() - new Date(b.start.dateTime || b.start.date).getTime();
};
//Overwrites defaultSettings values with overrideSettings and adds overrideSettings if non existent in defaultSettings
var mergeOptions = function(defaultSettings, overrideSettings){
var newObject = {},
i;
for (i in defaultSettings) {
newObject[i] = defaultSettings[i];
}
for (i in overrideSettings) {
newObject[i] = overrideSettings[i];
}
return newObject;
};
var isAllDay = function (dateStart, dateEnd) {
var dateStartFormatted = getDateFormatted(dateStart),
dateEndFormatted = getDateFormatted(dateEnd);
//if start date is midnight and the end date a following day midnight as well
if ((dateStartFormatted.getTime() === dateEndFormatted.getTime() - 86400000) &&
dateStartFormatted.getMinutes() === 0 &&
dateStartFormatted.getHours() === 0) {
return true;
}
return false;
};
//Get all necessary data (dates, location, summary, description) and creates a list item
var transformationList = function(result, tagName, format) {
var dateStart = getDateInfo(result.start.dateTime || result.start.date),
dateEnd = getDateInfo(result.end.dateTime || result.end.date),
moreDaysEvent = (typeof result.end.date !== 'undefined'),
dayNames = config.dayNames,
isAllDayEvent = isAllDay(dateStart, dateEnd);
if (moreDaysEvent) {
dateStart = addOneDay(dateStart);
}
if (isAllDayEvent) {
dateEnd = subtractOneMinute(dateEnd);
}
var dateFormatted = getFormattedDate(dateStart, dateEnd, moreDaysEvent, isAllDayEvent, dayNames),
output = '<' + tagName + '>',
summary = result.summary || '',
description = result.description || '',
location = result.location || '',
i;
for (i = 0; i < format.length; i++) {
format[i] = format[i].toString();
if (format[i] === '*summary*') {
output = output.concat('<span class="summary">' + summary + '</span>');
} else if (format[i] === '*date*') {
output = output.concat('<span class="date">' + dateFormatted + '</span>');
} else if (format[i] === '*description*') {
output = output.concat('<span class="description">' + description + '</span>');
} else if (format[i] === '*location*') {
output = output.concat('<span class="location">' + location + '</span>');
} else {
if ((format[i + 1] === '*location*' && location !== '') ||
(format[i + 1] === '*summary*' && summary !== '') ||
(format[i + 1] === '*date*' && dateFormatted !== '') ||
(format[i + 1] === '*description*' && description !== '')) {
output = output.concat(format[i]);
}
}
}
return output + '</' + tagName + '>';
};
//Check if date is later then now
var isPast = function(date) {
var compareDate = new Date(date),
now = new Date();
if (now.getTime() > compareDate.getTime()) {
return true;
}
return false;
};
//Get temp array with information abou day in followin format: [day number, month number, year, hours, minutes]
var getDateInfo = function(date) {
date = new Date(date);
return [date.getDate(), date.getMonth(), date.getFullYear(), date.getHours(), date.getMinutes(), 0, 0];
};
//Get month name according to index
var getMonthName = function (month) {
var monthNames = [
'Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli',
'August', 'September', 'Oktober', 'November', 'Dezember'
];
return monthNames[month];
};
var getDayName = function (day) {
var dayNames = [
'Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'
];
return dayNames[day];
};
var getDayNameFormatted = function (dateFormatted) {
return getDayName(getDateFormatted(dateFormatted).getDay()) + ' ';
};
var getDateFormatted = function (dateInfo) {
return new Date(dateInfo[2], dateInfo[1], dateInfo[0], dateInfo[3], dateInfo[4] + 0, 0);
};
//Add one day
var addOneDay = function (dateInfo) {
var date = getDateFormatted(dateInfo);
date.setTime(date.getTime() + 86400000);
return getDateInfo(date);
};
//Subtract one day
var subtractOneDay = function (dateInfo) {
var date = getDateFormatted(dateInfo);
date.setTime(date.getTime() - 86400000);
return getDateInfo(date);
};
//Subtract one minute
var subtractOneMinute = function (dateInfo) {
var date = getDateFormatted(dateInfo);
date.setTime(date.getTime() - 60000);
return getDateInfo(date);
};
//Transformations for formatting date into human readable format
var formatDateSameDay = function(dateStart, dateEnd, moreDaysEvent, isAllDayEvent, dayNames) {
var formattedTime = '',
dayNameStart = '';
if (dayNames) {
dayNameStart = getDayNameFormatted(dateStart);
}
if (config.sameDayTimes && !moreDaysEvent && !isAllDayEvent) {
formattedTime = ' from ' + getFormattedTime(dateStart) + ' - ' + getFormattedTime(dateEnd);
}
//month day, year time-time
return dayNameStart + dateStart[0] + '. ' + getMonthName(dateStart[1]) + ', ' + dateStart[2] + formattedTime;
};
var formatDateOneDay = function(dateStart, dayNames) {
var dayName = '';
if (dayNames) {
dayName = getDayNameFormatted(dateStart);
}
//month day, year
return dayName + dateStart[0] + '. ' + getMonthName(dateStart[1]) + ', ' + dateStart[2];
};
var formatDateDifferentDay = function(dateStart, dateEnd, dayNames) {
var dayNameStart = '',
dayNameEnd = '';
if (dayNames) {
dayNameStart = getDayNameFormatted(dateStart);
dayNameEnd = getDayNameFormatted(dateEnd);
}
//month day-day, year
return dayNameStart + getMonthName(dateStart[1]) + ' ' + dateStart[0] + '-' + dayNameEnd + dateEnd[0] + ', ' + dateStart[2];
};
var formatDateDifferentMonth = function(dateStart, dateEnd, dayNames) {
var dayNameStart = '',
dayNameEnd = '';
if (dayNames) {
dayNameStart = getDayNameFormatted(dateStart);
dayNameEnd = getDayNameFormatted(dateEnd);
}
//month day - month day, year
return dayNameStart + dateStart[0] + '. ' + getMonthName(dateStart[1]) + ' ' + '-' + dayNameEnd + dateEnd[0] + '. ' + getMonthName(dateEnd[1]) + ', ' + dateStart[2];
};
var formatDateDifferentYear = function(dateStart, dateEnd, dayNames) {
var dayNameStart = '',
dayNameEnd = '';
if (dayNames) {
dayNameStart = getDayNameFormatted(dateStart);
dayNameEnd = getDayNameFormatted(dateEnd);
}
//month day, year - month day, year
return dayNameStart + dateStart[0] + '. ' + getMonthName(dateStart[1]) + ', ' + dateStart[2] + '-' + dayNameEnd + dateEnd[0] + '. ' + getMonthName(dateEnd[1]) + ', ' + dateEnd[2];
};
//Check differences between dates and format them
var getFormattedDate = function(dateStart, dateEnd, moreDaysEvent, isAllDayEvent, dayNames) {
var formattedDate = '';
if (dateStart[0] === dateEnd[0]) {
if (dateStart[1] === dateEnd[1]) {
if (dateStart[2] === dateEnd[2]) {
//month day, year
formattedDate = formatDateSameDay(dateStart, dateEnd, moreDaysEvent, isAllDayEvent, dayNames);
} else {
//month day, year - month day, year
formattedDate = formatDateDifferentYear(dateStart, dateEnd, dayNames);
}
} else {
if (dateStart[2] === dateEnd[2]) {
//month day - month day, year
formattedDate = formatDateDifferentMonth(dateStart, dateEnd, dayNames);
} else {
//month day, year - month day, year
formattedDate = formatDateDifferentYear(dateStart, dateEnd, dayNames);
}
}
} else {
if (dateStart[1] === dateEnd[1]) {
if (dateStart[2] === dateEnd[2]) {
//month day-day, year
formattedDate = formatDateDifferentDay(dateStart, dateEnd, dayNames);
} else {
//month day, year - month day, year
formattedDate = formatDateDifferentYear(dateStart, dateEnd, dayNames);
}
} else {
if (dateStart[2] === dateEnd[2]) {
//month day - month day, year
formattedDate = formatDateDifferentMonth(dateStart, dateEnd, dayNames);
} else {
//month day, year - month day, year
formattedDate = formatDateDifferentYear(dateStart, dateEnd, dayNames);
}
}
}
return formattedDate;
};
var getFormattedTime = function (date) {
var formattedTime = '',
period = 'Uhr',
hour = date[3],
minute = date[4];
// Handle afternoon.
if (hour >= 12) {
period = 'Uhr';
}
// Handle midnight.
if (hour === 0) {
hour = 0;
}
// Ensure 2-digit minute value.
minute = (minute < 10 ? '0' : '') + minute;
// Format time.
formattedTime = hour + ':' + minute + period;
return formattedTime;
};
return {
init: function (settingsOverride) {
var settings = {
calendarUrl: 'https://www.googleapis.com/calendar/v3/calendars/milan.kacurak#gmail.com/events?key=AIzaSyCR3-ptjHE-_douJsn8o20oRwkxt-zHStY',
past: true,
upcoming: true,
sameDayTimes: true,
dayNames: true,
pastTopN: -1,
upcomingTopN: -1,
recurringEvents: true,
itemsTagName: 'li',
upcomingSelector: '#events-upcoming',
pastSelector: '#events-past',
upcomingHeading: '<h2>Upcoming events</h2>',
pastHeading: '<h2>Past events</h2>',
format: ['*date*', ': ', '*summary*', ' — ', '*description*', ' in ', '*location*']
};
settings = mergeOptions(settings, settingsOverride);
init(settings);
}
};
})();
Can you explain me based on my code how I can re-run the js every 10min? I am not sure where I have to put setIntervall(?????????,10*60*1000)?
Try to put formatGoogleCalendar.init() in a setInterval, like this :
setInterval(function(){
formatGoogleCalendar.init({
calendarUrl: 'https://www.googleapis.com/calendar/v3/calendars/magic.kfs#gmx.de/events?key=AIzaSyDei0zrhHPHAtYc5x7vjdUmGaC3FlFnm1Y ',
past: true,
upcoming: true,
sameDayTimes: true,
pastTopN: 20,
upcomingTopN: 4,
recurringEvents: true,
itemsTagName: 'ul',
upcomingSelector: '#events-upcoming',
pastSelector: '#events-past',
upcomingHeading: '<div id="Termine" >Kommende Termine</div> ',
pastHeading: '<p><h2 class="medium left">Vergangene Termine</h2></p>',
format: ['*date*', ': ', '*summary*', ' — ', '*description*', ' in ', '*location*']
});
}, 600000);
Move your init into a function and call that function in the setInterval() every 10 minutes.
<script>
function calendarInit(){
formatGoogleCalendar.init({
calendarUrl: 'https://www.googleapis.com/calendar/v3/calendars/magic.kfs#gmx.de/events?key=AIzaSyDei0zrhHPHAtYc5x7vjdUmGaC3FlFnm1Y ',
past: true,
upcoming: true,
sameDayTimes: true,
pastTopN: 20,
upcomingTopN: 4,
recurringEvents: true,
itemsTagName: 'ul',
upcomingSelector: '#events-upcoming',
pastSelector: '#events-past',
upcomingHeading: '<div id="Termine" >Kommende Termine</div> ',
pastHeading: '<p><h2 class="medium left">Vergangene Termine</h2></p>',
format: ['*date*', ': ', '*summary*', ' — ', '*description*', ' in ', '*location*']
});
}
var cal = setInterval(calendarInit(), 10*60*1000);
Well you can use
setInterval(function, delay)
delay is in milliseconds and function is the name of the function you want to call. Therefore, you need to wrap your content of js file within a function as
function callAgain()
{
var formatGoogleCalendar = (function() {
'use strict';
var config;
.
.
.
}
and then use the setInterval(callAgain, 5000) in the script part of your html file
I have a time/date converter. When the user enters "130" for example it returns "06/07/2016 01:30:00" when they enter "6 7 16" for example it returns "06/07/2016 00:00:00" but when the user enters "6 7 16 130" for example it returns "06/07/2016 false:00"
Here is my relevant code (can show more if need be):
function checkDateTime(val) {
var nowDate = new Date();
var month, day, year, time;
var ar;
if (eval(val)) {
var tval = val.value;
ar = tval.split(' ');
if (ar.length === 3) { // i.e. if it's supposed to be a date
ar[0] = month;
ar[1] = day;
ar[2] = year;
document.getElementById("FromDate").value = CheckDate(val) + ' ' + '00:00:00';
//checkDate(ar[0] + ' ' + ar[1] + ' ' + ar[2]);
}
//alert(LeftPadZero(ar[0]) + ' ' + LeftPadZero(ar[1]) + ' ' + LeftPadZero(ar[2]));
//alert(CheckDate(ar[0] + ' ' + ar[1] + ' ' + ar[2]));
if (ar.length === 1) { // if it's a time
ar[0] = time;
var MM = nowDate.getMonth() + 1;
var DD = nowDate.getDate();
var Y = nowDate.getFullYear();
var nowDateFormat = LeftPadZero(MM) + '/' + LeftPadZero(DD) + '/' + Y;
alert(ar[0]);
document.getElementById("FromDate").value = nowDateFormat + ' ' + checktime(val) + ':00';
}
if (ar.length === 4) { // if date and time
ar[0] = month;
// alert(ar[0]);
ar[1] = day;
// alert(ar[1]);
ar[2] = year;
// alert(ar[2]);
ar[3] = time;
// alert(ar[3]);
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(val) + ':00';
// alert(ar[0] + ' ' + ar[1] + ' ' + ar[2] + ' ' + ar[3]);
}
}
}
function CheckDate(theobj) {
var isInvalid = 0;
var themonth, theday, theyear;
var arr;
if (eval(theobj)) {
var thevalue = theobj.value;
arr = thevalue.split(" ");
if (arr.length < 2) {
arr = thevalue.split("/");
if (arr.length < 2) {
arr = thevalue.split("-");
if (arr.length < 2) {
isInvalid = 1;
}
}
}
if (isInvalid == 0) {
themonth = arr[0];
theday = arr[1];
if (arr.length == 3) {
theyear = arr[2];
} else {
theyear = new Date().getFullYear();
}
if (isNaN(themonth)) {
themonth = themonth.toUpperCase();
//month name abbreviation array
var montharr = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
for (i = 0; i < montharr.length; i++) {
//if the first 3 characters of month name matches
if (themonth.substring(0, 3) == montharr[i]) {
themonth = i + 1;
break;
}
}
} else {
if (themonth < 1 || themonth > 12) {
isInvalid = 1;
}
}
}
if (isNaN(themonth) || isNaN(theday) || isNaN(theyear)) {
isInvalid = 1;
}
if (isInvalid == 0) {
var thedate = LeftPadZero(themonth) + "/" + LeftPadZero(theday) + "/" + LeftPadZero(theyear);
return thedate;
} else {
return false;
}
}
}
function checktime(x) {
var tempchar = new String;
tempchar = MakeNum(x);
if (tempchar != '' && tempchar.length < 4) {
//e.g., if they enter '030' make it '0030'
if (tempchar.length == 3) {
tempchar='0' + tempchar;
}
//e.g, if they enter '11' make it '1100'
if (tempchar.length == 2) {
tempchar=tempchar + '00';
}
//e.g, if they enter '6' make it '0600'
if (tempchar.length == 1) {
tempchar='0' + tempchar + '00';
}
}
if (tempchar==null || tempchar == '') {
return false;
}
else {
if (tempchar=='2400') {
return false;
}else{
var tempnum= new Number(tempchar);
var swmin = new Number(tempnum % 100);
var swhour = new Number((tempnum-swmin)/100);
if (swhour < 25 && swmin < 60) {
x = LeftPadZero(swhour) + ":" + LeftPadZero(swmin);
return x;
}
else {
return false;
}
}
}
return false;
/*
if(eval(changecount)!=null){
changecount+=1;
}
*/
}
function MakeNum(x) {
var tstring = new String(x.value);
var tempchar = new String;
var f = 0;
for (var i = 0; i < tstring.length; i++) {
// walk through the string and remove all non-digits
chr = tstring.charAt(i);
if (isNaN(chr)) {
f=f;
}
else {
tempchar += chr;
f++;
}
}
return tempchar;
}
I have tried numerous things to figure out why the time element returns false in an array of length 4, but not an array length 1 for some reason, including setting various alerts and checking the console. I have googled this problem several times and came up empty.
To reiterate, my problem is that the time element returns false in an array of 4, and what I am trying to accomplish is for the user to input a date and time and have them both formatted and displayed correctly.
Can anybody help and/or offer any advice and/or suggestions? Thanks!
Edit: user enters '130' should convert to '06/07/2016(today's date) 01:30:00'
6 7 16 should convert to '06/07/2016 00:00:00'
6 7 16 130 should convert to '06/07/2016 01:30:00'
There seems to be some missing parts here... various functions and whatever input type these ones need are excluded from your post... However, taking a guess, I'm going to say that when you are making your final "checktime" call, rather than passing the full "val" variable, you should just be passing the last chunk of your split input, "ar[3]" in this case. That way, only that piece is evaluated by the function.
IE:
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(val) + ':00';
should be
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(ar[3]) + ':00';
Again, this is just a guess due to the missing pieces.
Edit:
After getting some additional details, the issue DOES seem to be in the data being sent to the checktime function, however, due to the current code setup, the fix is actually just making sure that the data being processed by the checktime function is only the last item in the array... see below for the correction within the checktime function:
tempchar = MakeNum(x);
becomes
tempchar = MakeNum(x).split(' ').pop();
Here is my code. It currently creates this:
but I need it to display the days of the week below the dates. I know its probably just a matter of switching 2 lines around but my javascript skills are limited and i'm struggling. any help greatly appreciated.
var Timeline = function (container, date) {
this.daysPerMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
this.weekDays = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
this.monthsOfYear = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
this.dayNumbers = {
"sunday": 0,
"monday": 1,
"tuesday": 2,
"wednesday": 3,
"thursday": 4,
"friday": 5,
"saturday": 6
};
this.initialize = function () {
this.isIE6 = (jQuery.browser.msie && jQuery.browser.version == "6.0");
this.container = $("#" + container);
if (!this.container.length) {
alert("can not locate container element \"" + container + "\"!");
return;
}
this.bubble = new Timeline.Bubble(this);
this.date = (date) ? date : new Date();
this.readEvents();
this.placeHolders = this.setupPlaceHolders();
this.container.addClass("timeline");
this.render();
},
this.readEvents = function () {
this.events = [];
var eventList = this.container.find("ul");
var eventItems = eventList.find("li");
for (var i = 0; i < eventItems.length; i++) {
var date = new Date(eventItems[i].getAttribute("title"));
if (date == "Invalid Date") continue;
this.events[i] = {
name: eventItems[i].className,
date: date,
day: date.getDate(),
month: date.getMonth(),
year: date.getFullYear(),
content: jQuery(eventItems[i]).html()
};
}
var j, tmp, events = this.events;
for (var i = 1; i < events.length; i++) {
tmp = this.events[i];
for (j = i; j > 0 && events[j - 1].date > tmp.date; j--)
events[j] = events[j - 1];
events[j] = tmp;
}
eventList.remove();
}
this.render = function () {
this.placeHolders.arrows.empty();
this.placeHolders.top.empty();
this.placeHolders.bottom.empty();
var monthRepresentation = this.getMonthRepresentation();
for (var i = 0; i < monthRepresentation.length; i++)
this.renderDay(this.placeHolders.top, this.placeHolders.bottom, monthRepresentation[i]);
if (this.isIE6) this.handleIE6Issues();
this.setupArrows();
}
this.handleIE6Issues = function () {
var clone = this.placeHolders.top.clone(true);
this.container.append(clone);
clone.css({
left: "-1000px",
top: "-1000px"
});
var width = clone.outerWidth();
clone.remove();
this.placeHolders.top.css({
width: width + "px"
});
this.placeHolders.bottom.css({
width: width + "px"
});
}
this.renderDay = function (topRow, bottomRow, data) {
var cssClass = "";
cssClass += (this.isToday(data.number)) ? "today" : "";
cssClass += (data.events.length) ? " event" : "";
topRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.name + "</div></li>");
bottomRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.number + "</div></li>");
nameEl = topRow.find("div:last");
numbEl = bottomRow.find("div:last");
if (data.events.length == 0) return;
var self = this;
var enterClosure = function (e) {
self.onMouseEnter(e);
};
var leaveClosure = function (e) {
self.onMouseLeave(e);
};
nameEl.bind("mouseenter", data, enterClosure);
numbEl.bind("mouseenter", data, enterClosure);
nameEl.bind("mouseleave", data, leaveClosure);
numbEl.bind("mouseleave", data, leaveClosure);
}
this.setupArrows = function () {
var dateString = this.monthsOfYear[this.date.getMonth()] + " " + this.date.getFullYear();
var html = "";
html += "<div class=\"timeline_lastyear\" title=\"Previous Year\"></div>"
html += "<div class=\"timeline_lastmonth\" title=\"Previous Month\"></div>"
html += "<div class=\"timeline_date\">" + dateString + "</div>"
html += "<div class=\"timeline_nextmonth\" title=\"Next Month\"></div>"
html += "<div class=\"timeline_nextyear\" title=\"Next Year\"></div>"
this.placeHolders.arrows.append(html);
var children = this.placeHolders.arrows.children();
var self = this;
$(children[0]).bind("click", this, function () {
self.previousYear()
});
$(children[1]).bind("click", this, function () {
self.previousMonth()
});
$(children[3]).bind("click", this, function () {
self.nextMonth()
});
$(children[4]).bind("click", this, function () {
self.nextYear()
});
}
this.getEventsForDay = function (dayNumber) {
var result = [];
for (var i = 0; i < this.events.length; i++) {
var e = this.events[i];
if (e.day == dayNumber && e.month == this.date.getMonth() && e.year == this.date.getFullYear()) result.push(this.events[i]);
}
return result;
}
this.setupPlaceHolders = function () {
var arrows = jQuery(document.createElement("div"));
arrows.addClass("timeline_arrows");
var bottom = jQuery(document.createElement("div"));
bottom.addClass("timeline_bottom");
var top = jQuery(document.createElement("div"));
top.addClass("timeline_top");
top.append("<ul></ul>");
bottom.append("<ul></ul>");
this.container.append([arrows[0], top[0], bottom[0]]);
return {
arrows: arrows,
bottom: bottom.find("ul:first"),
top: top.find("ul:first")
};
}
this.getMonthRepresentation = function () {
var result = [];
var numberOfDays = this.getNumberOfDaysInMonth(this.date);
var firstDay = this.getFirstDayOfMonth(this.date);
var finished = false;
for (var i = 0; i < numberOfDays; i++) {
result.push({
name: this.weekDays[firstDay].substring(0, 3),
number: (i + 1 < 10) ? "0" + (i + 1) : (i + 1),
events: this.getEventsForDay(i + 1)
});
firstDay = (firstDay == 6) ? 0 : ++firstDay;
}
return result;
}
this.getNumberOfDaysInMonth = function (dateObject) {
var month = dateObject.getMonth();
if (month == 1) {
var leapYear = (new Date(dateObject.getYear(), 1, 29).getDate()) == 29;
if (leapYear) return 29
else return 28;
} else return this.daysPerMonth[month];
},
this.getFirstDayOfMonth = function (dateObject) {
var save = dateObject.getDate();
dateObject.setDate(1);
var result = dateObject.getDay();
dateObject.setDate(save);
return result;
},
this.isToday = function (dayNumber) {
var today = new Date();
return (today.getDate() == dayNumber && today.getFullYear() == this.date.getFullYear() && today.getMonth() == this.date.getMonth());
},
this.onMouseEnter = function (event) {
var left = $(event.target).offset().left;
var width = $(event.target).outerWidth();
this.bubble.setContent(event.data.events);
this.bubble.show(left + (width / 2));
}
this.onMouseLeave = function (event) {
this.bubble.hide();
}
this.nextMonth = function () {
this.date.setMonth(this.date.getMonth() + 1);
this.render();
}
this.nextYear = function () {
this.date.setYear(this.date.getFullYear() + 1);
this.render();
}
this.previousMonth = function () {
this.date.setMonth(this.date.getMonth() - 1);
this.render();
}
this.previousYear = function () {
this.date.setYear(this.date.getFullYear() - 1);
this.render();
}
this.initialize();
}
Timeline.Bubble = function (timeline) {
this.initialize = function () {
var IE6Class = (timeline.isIE6) ? " bubbleIE6" : "";
var id = "bubble_" + new Date().getTime();
var html = "";
html += "<div id=\"" + id + "\" class=\"timeline_bubble\">";
html += "<div class=\"bubble_top" + IE6Class + "\"></div>";
html += "<div class=\"bubble_mid" + IE6Class + "\"></div>";
html += "<div class=\"bubble_bottom" + IE6Class + "\"></div></div>";
timeline.container.after(html);
this.container = $("#" + id);
this.container.bind("mouseenter", this, this.onMouseEnter);
this.container.bind("mouseleave", this, this.onMouseLeave);
}
this.onMouseEnter = function (event) {
event.data.stopHiding();
}
this.onMouseLeave = function (event) {
event.data.hide();
}
this.stopHiding = function () {
if (this.goingOffHandle && this.goingOffHandle != null) {
clearTimeout(this.goingOffHandle);
this.goingOffHandle = null;
}
}
this.setContent = function (events) {
this.stopHiding();
var html = "";
for (var i = 0; i < events.length; i++)
html += "<div><div class=\"event_title\">" + events[i].name + "<p class=\"event_data\">" + events[i].content + "</p></div></div>";
var midSection = $(this.container.children()[1]);
midSection.empty();
midSection.append(html);
var titles = midSection.find(".event_title");
titles.each(function (inx, element) {
$(element).bind("mouseenter", function (event) {
$(element).children(":first").animate({
opacity: "toggle"
}, 200);
});
$(element).bind("mouseleave", function (event) {
$(element).children(":first").animate({
opacity: "hide"
}, 200);
});
});
}
this.show = function (at) {
this.container.animate({
opacity: "show"
}, 250);
this.container.animate({
left: at - (this.container.outerWidth() / 2)
}, 300);
}
this.hide = function () {
var self = this;
this.goingOffHandle = setTimeout(function () {
self.container.animate({
opacity: "hide"
}, 250);
}, 700);
}
this.initialize();
}
In this.renderDay try inverting the two .append lines :
topRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.name + "</div></li>");
bottomRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.number + "</div></li>");
so that it reads
bottomRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.number + "</div></li>");
topRow.append("<li class=\"" + data.name + "\"><div class=\"" + cssClass + "\">" + data.name + "</div></li>");