I have an array that will always contain days of the week as input. I have a const array of ordered days of the week to compare to. I first sort the input array by comparing the index of the array with the const array.
Now, I can loop through the input array to find the index between two values and determine if they are consecutive. After this point, I am lost on how to create the output I want.
For example, I have input array:
[sun, mon, tue, thu, fri]
and I want to output as:
sun to tues, thu, fri
Edit
Sorry I didn't post my attempt when it was originally posted. Please see below:
const days = [
'sun',
'mon',
'tues',
'wed',
'thurs',
'fri',
'sat',
];
export const combineDays = (inputDays) => {
const sortedArray = inputDays
.map((day) => {
return days.indexOf(day);
})
.sort((a, b) => {
return a - b;
});
// the string I want to return
let dayRange = '';
//variable to hold previous day if consecutive
let rangeEnd = '';
//range position in the loop
let rangePos = 0;
sortedArray.forEach((day) => {
if (dayRange === '') {
dayRange = days[day];
rangePos = days.indexOf(days[day]) + 1;
} else if (days.indexOf(days[day]) === rangePos) {
rangeEnd = days[day];
rangePos++;
} else if ((days.indexOf(days[day]) !== rangePos) & (rangeEnd !== '')) {
dayRange = dayRange + ' to ' + rangeEnd + ', ' + days[day];
rangePos = days.indexOf(days[day]) + 1;
rangeEnd = '';
} else {
dayRange = dayRange + ', ' + days[day];
rangeEnd = '';
rangePos = days.indexOf(days[day]) + 1;
}
});
return dayRange;
};
Try the following code:
const array = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
const inputArray = ['fri','thu', 'sat'];
let indexArray = inputArray.map(item => {
return array.indexOf(item);
});
let outputArray = indexArray.sort(function(a, b){return a-b}).map(item =>
array[item]);
// EXPECTED RESULT: ["thu","fri","sat"]
console.log(outputArray);
And things are gonna work
After trying for a few more hours, I got it to work but it doesn't seem DRY:
const days = [
'sun',
'mon',
'tue',
'wed',
'thu',
'fri',
'sat',
];
export const combineDays = (inputDays) => {
const sortedArray = inputDays
.map((day) => {
return days.indexOf(day);
})
.sort((a, b) => {
return a - b;
});
let dayRange = '';
let range = false;
let rangeEnd = '';
let rangePos = 0;
sortedArray.forEach((day, index) => {
if (dayRange === '') {
dayRange = days[day];
rangePos = day + 1;
} else if (day === rangePos) {
if (rangeEnd !== '') {
range = true;
} else {
range = false;
}
if (index !== sortedArray.length - 1) {
rangeEnd = days[day];
rangePos++;
} else {
if (range === true) {
dayRange = dayRange + ' to ' + days[day];
} else if (rangeEnd !== '') {
dayRange = dayRange + ', ' + rangeEnd + ', ' + days[day];
} else {
dayRange = dayRange + ', ' + days[day];
}
}
} else if (day !== rangePos) {
if (range === true) {
dayRange = dayRange + ' to ' + rangeEnd;
} else {
dayRange = dayRange + ', ' + rangeEnd;
}
dayRange = dayRange + ', ' + days[day];
rangePos = day + 1;
rangeEnd = '';
}
});
return dayRange;
};
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 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();
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
I want to list all dates between 2 dates like..
list_dates('06/27/2013','07/31/2013');
This function will return all dates between 06/27/2013 - 07/31/2013 in array like..
['06/27/2013','06/28/2013','06/29/2013','06/30/2013','07/01/2013','...so_on..','07/31/2013'];
This function will work in all cases , Like older to newer , newer to older , or same dates like..
list_dates('06/27/2013','07/31/2013');
list_dates('07/31/2013','06/27/2013');
list_dates('07/31/2013','07/31/2013');
I do like...
function list_dates(a,b) {
var list = [];
var a_date = new Date(a);
var b_date = new Date(b);
if (a_date > b_date) {
} else if (a_date < b_date) {
} else {
list.push(a);
}
return list;
}
Demo : http://jsfiddle.net/fSGQ6/
But how to get dates between 2 dates ?
try this
list_dates('11/27/2013', '12/31/2013');
list_dates('03/21/2013', '02/14/2013');
list_dates('07/31/2013', '07/31/2013');
function list_dates(a, b) {
var list = [];
var a_date = new Date(a);
var b_date = new Date(b);
if (a_date > b_date) {
while (a_date >= b_date) {
var date_format = ('0' + (b_date.getMonth() + 1)).slice(-2) + '/' + ('0' + b_date.getDate()).slice(-2) + '/' + b_date.getFullYear();
list.push(date_format);
b_date = new Date(b_date.setDate(b_date.getDate() + 1));
}
} else if (a_date < b_date) {
while (b_date >= a_date) {
var date_format = ('0' + (a_date.getMonth() + 1)).slice(-2) + '/' + ('0' + a_date.getDate()).slice(-2) + '/' + a_date.getFullYear();
list.push(date_format);
a_date = new Date(a_date.setDate(a_date.getDate() + 1));
}
} else {
list.push(a);
}
console.log(list);
}
UPDATE: as poster requirement
var start = new Date(2013,06,27);
var end = new Date(2013,07,31);
var result =[];
var loop = true;
while(loop){
console.log(start.toISOString);
result.push(start);
start.setDate(start.getDate()+1)
if(start>end){
loop = false;
}
}
Date.prototype.getShortDate = function () {
// Do formatting of string here
return (this.getMonth() + 1) + "/" + this.getDate() + "/" + this.getFullYear();
}
function list_dates(a, b) {
var a_date = new Date(a),
b_date = new Date(b),
list = [a_date.getShortDate()],
change = (a_date > b_date ? -1 : 1);
while (a_date.getTime() != b_date.getTime()) {
a_date.setDate(a_date.getDate() + change);
list.push(a_date.getShortDate());
}
return list;
}