Skip to content

Instantly share code, notes, and snippets.

@masudiiuc
Last active January 3, 2016 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masudiiuc/8448437 to your computer and use it in GitHub Desktop.
Save masudiiuc/8448437 to your computer and use it in GitHub Desktop.
CustomDateManager has the following functionality : 1. Date change with prev, next and custom date selection 2. Week change with prev, next and custom date selection 3. Date range selection with date range picker
/**
* version 2.1.20
* @license
* =========================================================
* bootstrap-datetimepicker.js
* http://www.eyecon.ro/bootstrap-datepicker
* =========================================================
* Copyright 2012 Stefan Petre
*
* Contributions:
* - updated for Bootstrap v3 by Jonathan Peterson (@Eonasdan) and (almost)
* completely rewritten to use Momentjs
* - based on tarruda's bootstrap-datepicker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================================================
*
* MODIFICATION:
*
* 228: //change by masud
* 229: offset.top = offset.top + picker.element.outerHeight() -45;
*
*/
; (function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD is used - Register as an anonymous module.
define(['jquery', 'moment'], factory);
} else {
// AMD is not used - Attempt to fetch dependencies from scope.
if(!jQuery){
throw 'bootstrap-datetimepicker requires jQuery to be loaded first';
}else if(!moment) {
throw 'bootstrap-datetimepicker requires moment.js to be loaded first';
}else{
factory(jQuery, moment);
}
}
}
(function ($, moment) {
if (typeof moment === 'undefined') {
alert("momentjs is requried");
throw new Error('momentjs is requried');
};
var dpgId = 0,
pMoment = moment,
// ReSharper disable once InconsistentNaming
DateTimePicker = function (element, options) {
var defaults = {
pickDate: true,
pickTime: true,
useMinutes: true,
useSeconds: false,
minuteStepping: 1,
startDate: new pMoment({ y: 1970 }),
endDate: new pMoment().add(50, "y"),
collapse: true,
language: "en",
defaultDate: "",
disabledDates: [],
enabledDates: false,
icons: {},
useStrict: false
},
icons = {
time: 'glyphicon glyphicon-time',
date: 'glyphicon glyphicon-calendar',
up: 'glyphicon glyphicon-chevron-up',
down: 'glyphicon glyphicon-chevron-down'
},
picker = this,
init = function () {
var icon = false, i, dDate, longDateFormat;
picker.options = $.extend({}, defaults, options);
picker.options.icons = $.extend({}, icons, picker.options.icons);
picker.element = $(element);
dataToOptions();
if (!(picker.options.pickTime || picker.options.pickDate))
throw new Error('Must choose at least one picker');
picker.id = dpgId++;
pMoment.lang(picker.options.language);
picker.date = pMoment();
picker.unset = false;
picker.isInput = picker.element.is('input');
picker.component = false;
if (picker.element.hasClass('input-group')) {
if (picker.element.find('.datepickerbutton').size() == 0) {//in case there is more then one 'input-group-addon` #48
picker.component = picker.element.find("[class^='input-group-']");
}
else {
picker.component = picker.element.find('.datepickerbutton');
}
}
picker.format = picker.options.format;
longDateFormat = pMoment()._lang._longDateFormat;
if (!picker.format) {
if (picker.isInput) picker.format = picker.element.data('format');
else picker.format = picker.element.find('input').data('format');
if (!picker.format) {
picker.format = (picker.options.pickDate ? longDateFormat.L : '');
if (picker.options.pickDate && picker.options.pickTime) picker.format += ' ';
picker.format += (picker.options.pickTime ? longDateFormat.LT : '');
if (picker.options.useSeconds) {
if (~longDateFormat.LT.indexOf(' A')) {
picker.format = picker.format.split(" A")[0] + ":ss A";
}
else {
picker.format += ':ss';
}
}
}
}
picker.options.use24hours = picker.format.toLowerCase().indexOf("a") < 1;
if (picker.component) icon = picker.component.find('span');
if (picker.options.pickTime) {
if (icon) icon.addClass(picker.options.icons.time);
}
if (picker.options.pickDate) {
if (icon) {
icon.removeClass(picker.options.icons.time);
icon.addClass(picker.options.icons.date);
}
}
picker.widget = $(getTemplate(picker.options.pickDate, picker.options.pickTime, picker.options.collapse)).appendTo('body');
picker.minViewMode = picker.options.minViewMode || picker.element.data('date-minviewmode') || 0;
if (typeof picker.minViewMode === 'string') {
switch (picker.minViewMode) {
case 'months':
picker.minViewMode = 1;
break;
case 'years':
picker.minViewMode = 2;
break;
default:
picker.minViewMode = 0;
break;
}
}
picker.viewMode = picker.options.viewMode || picker.element.data('date-viewmode') || 0;
if (typeof picker.viewMode === 'string') {
switch (picker.viewMode) {
case 'months':
picker.viewMode = 1;
break;
case 'years':
picker.viewMode = 2;
break;
default:
picker.viewMode = 0;
break;
}
}
for (i = 0; i < picker.options.disabledDates.length; i++) {
dDate = picker.options.disabledDates[i];
dDate = pMoment(dDate);
//if this is not a valid date then set it to the startdate -1 day so it's disabled.
if (!dDate.isValid()) dDate = pMoment(picker.options.startDate).subtract(1, "day");
picker.options.disabledDates[i] = dDate.format("L");
}
for (i = 0; i < picker.options.enabledDates.length; i++) {
dDate = picker.options.enabledDates[i];
dDate = pMoment(dDate);
//if this is not a valid date then set it to the startdate -1 day so it's disabled.
if (!dDate.isValid()) dDate = pMoment(picker.options.startDate).subtract(1, "day");
picker.options.enabledDates[i] = dDate.format("L");
}
picker.startViewMode = picker.viewMode;
picker.setStartDate(picker.options.startDate || picker.element.data('date-startdate'));
picker.setEndDate(picker.options.endDate || picker.element.data('date-enddate'));
fillDow();
fillMonths();
fillHours();
fillMinutes();
fillSeconds();
update();
showMode();
attachDatePickerEvents();
if (picker.options.defaultDate !== "") picker.setValue(picker.options.defaultDate);
},
dataToOptions = function () {
var eData = picker.element.data();
if (eData.pickdate !== undefined) picker.options.pickDate = eData.pickdate;
if (eData.picktime !== undefined) picker.options.pickTime = eData.picktime;
if (eData.useminutes !== undefined) picker.options.useMinutes = eData.useminutes;
if (eData.useseconds !== undefined) picker.options.useSeconds = eData.useseconds;
if (eData.minutestepping !== undefined) picker.options.minuteStepping = eData.minutestepping;
if (eData.startdate !== undefined) picker.options.startDate = eData.startdate;
if (eData.enddate !== undefined) picker.options.endDate = eData.enddate;
if (eData.collapse !== undefined) picker.options.collapse = eData.collapse;
if (eData.language !== undefined) picker.options.language = eData.language;
if (eData.defaultdate !== undefined) picker.options.defaultDate = eData.defaultdate;
if (eData.disableddates !== undefined) picker.options.disabledDates = eData.disableddates;
if (eData.enableddates !== undefined) picker.options.enabledDates = eData.enableddates;
if (eData.icons !== undefined) picker.options.icons = eData.icons;
if (eData.usestrict !== undefined) picker.options.useStrict = eData.usestrict;
},
place = function () {
var position = 'absolute',
offset = picker.component ? picker.component.offset() : picker.element.offset(), $window = $(window);
picker.width = picker.component ? picker.component.outerWidth() : picker.element.outerWidth();
//offset.top = offset.top + picker.element.outerHeight();
//change by masud
offset.top = offset.top + picker.element.outerHeight() -45;
//if (offset.top + picker.widget.height() > $window.height()) offset.top = offset.top - (picker.widget.height() + picker.height + 10);
if (picker.options.width !== undefined) {
picker.widget.width(picker.options.width);
}
if (picker.options.orientation === 'left') {
picker.widget.addClass('left-oriented');
offset.left = offset.left - picker.widget.width() + 20;
}
if (isInFixed()) {
position = 'fixed';
offset.top -= $window.scrollTop();
offset.left -= $window.scrollLeft();
}
if ($window.width() < offset.left + picker.widget.outerWidth()) {
offset.right = $window.width() - offset.left - picker.width;
offset.left = 'auto';
picker.widget.addClass('pull-right');
} else {
offset.right = 'auto';
picker.widget.removeClass('pull-right');
}
picker.widget.css({
position: position,
top: offset.top,
left: offset.left,
right: offset.right
});
},
notifyChange = function (oldDate, eventType) {
picker.element.trigger({
type: 'change.dp',
date: pMoment(picker.date),
oldDate: pMoment(oldDate)
});
if (eventType !== 'change')
picker.element.change();
},
notifyError = function (date) {
picker.element.trigger({
type: 'error.dp',
date: pMoment(date)
});
},
update = function (newDate) {
pMoment.lang(picker.options.language);
var dateStr = newDate;
if (!dateStr) {
if (picker.isInput) {
dateStr = picker.element.val();
} else {
dateStr = picker.element.find('input').val();
}
if (dateStr) picker.date = pMoment(dateStr, picker.format, picker.options.useStrict);
if (!picker.date) picker.date = pMoment();
}
picker.viewDate = pMoment(picker.date).startOf("month");
fillDate();
fillTime();
},
fillDow = function () {
pMoment.lang(picker.options.language);
var html = $('<tr>'), weekdaysMin = pMoment.weekdaysMin(), i;
if (pMoment()._lang._week.dow == 0) { // starts on Sunday
for(i = 0; i < 7; i++) {
html.append('<th class="dow">' + weekdaysMin[i] + '</th>');
}
} else {
for (i = 1; i < 8; i++) {
if (i == 7) {
html.append('<th class="dow">' + weekdaysMin[0] + '</th>');
} else {
html.append('<th class="dow">' + weekdaysMin[i] + '</th>');
}
}
}
picker.widget.find('.datepicker-days thead').append(html);
},
fillMonths = function () {
pMoment.lang(picker.options.language);
var html = '', i = 0, monthsShort = pMoment.monthsShort();
while (i < 12) {
html += '<span class="month">' + monthsShort[i++] + '</span>';
}
picker.widget.find('.datepicker-months td').append(html);
},
fillDate = function () {
pMoment.lang(picker.options.language);
var year = picker.viewDate.year(),
month = picker.viewDate.month(),
startYear = picker.options.startDate.year(),
startMonth = picker.options.startDate.month(),
endYear = picker.options.endDate.year(),
endMonth = picker.options.endDate.month(),
prevMonth, nextMonth, html = [], row, clsName, i, days, yearCont, currentYear, months = pMoment.months();
picker.widget.find('.datepicker-days').find('.disabled').removeClass('disabled');
picker.widget.find('.datepicker-months').find('.disabled').removeClass('disabled');
picker.widget.find('.datepicker-years').find('.disabled').removeClass('disabled');
picker.widget.find('.datepicker-days th:eq(1)').text(
months[month] + ' ' + year);
prevMonth = pMoment(picker.viewDate).subtract("months", 1);
days = prevMonth.daysInMonth();
prevMonth.date(days).startOf('week');
if ((year == startYear && month <= startMonth) || year < startYear) {
picker.widget.find('.datepicker-days th:eq(0)').addClass('disabled');
}
if ((year == endYear && month >= endMonth) || year > endYear) {
picker.widget.find('.datepicker-days th:eq(2)').addClass('disabled');
}
nextMonth = pMoment(prevMonth).add(42, "d");
while (prevMonth.isBefore(nextMonth)) {
if (prevMonth.weekday() === pMoment().startOf('week').weekday()) {
row = $('<tr>');
html.push(row);
}
clsName = '';
if (prevMonth.year() < year || (prevMonth.year() == year && prevMonth.month() < month)) {
clsName += ' old';
} else if (prevMonth.year() > year || (prevMonth.year() == year && prevMonth.month() > month)) {
clsName += ' new';
}
if (prevMonth.isSame(pMoment({ y: picker.date.year(), M: picker.date.month(), d: picker.date.date() }))) {
clsName += ' active';
}
if ((pMoment(prevMonth).add(1, "d") <= picker.options.startDate) || (prevMonth > picker.options.endDate) || isInDisableDates(prevMonth) || !isInEnableDates(prevMonth)) {
clsName += ' disabled';
}
row.append('<td class="day' + clsName + '">' + prevMonth.date() + '</td>');
prevMonth.add(1, "d");
}
picker.widget.find('.datepicker-days tbody').empty().append(html);
currentYear = pMoment().year(), months = picker.widget.find('.datepicker-months')
.find('th:eq(1)').text(year).end().find('span').removeClass('active');
if (currentYear === year) {
months.eq(pMoment().month()).addClass('active');
}
if (currentYear - 1 < startYear) {
picker.widget.find('.datepicker-months th:eq(0)').addClass('disabled');
}
if (currentYear + 1 > endYear) {
picker.widget.find('.datepicker-months th:eq(2)').addClass('disabled');
}
for (i = 0; i < 12; i++) {
if ((year == startYear && startMonth > i) || (year < startYear)) {
$(months[i]).addClass('disabled');
} else if ((year == endYear && endMonth < i) || (year > endYear)) {
$(months[i]).addClass('disabled');
}
}
html = '';
year = parseInt(year / 10, 10) * 10;
yearCont = picker.widget.find('.datepicker-years').find(
'th:eq(1)').text(year + '-' + (year + 9)).end().find('td');
picker.widget.find('.datepicker-years').find('th').removeClass('disabled');
if (startYear > year) {
picker.widget.find('.datepicker-years').find('th:eq(0)').addClass('disabled');
}
if (endYear < year + 9) {
picker.widget.find('.datepicker-years').find('th:eq(2)').addClass('disabled');
}
year -= 1;
for (i = -1; i < 11; i++) {
html += '<span class="year' + (i === -1 || i === 10 ? ' old' : '') + (currentYear === year ? ' active' : '') + ((year < startYear || year > endYear) ? ' disabled' : '') + '">' + year + '</span>';
year += 1;
}
yearCont.html(html);
},
fillHours = function () {
pMoment.lang(picker.options.language);
var table = picker.widget.find('.timepicker .timepicker-hours table'), html = '', current, i, j;
table.parent().hide();
if (picker.options.use24hours) {
current = 0;
for (i = 0; i < 6; i += 1) {
html += '<tr>';
for (j = 0; j < 4; j += 1) {
html += '<td class="hour">' + padLeft(current.toString()) + '</td>';
current++;
}
html += '</tr>';
}
}
else {
current = 1;
for (i = 0; i < 3; i += 1) {
html += '<tr>';
for (j = 0; j < 4; j += 1) {
html += '<td class="hour">' + padLeft(current.toString()) + '</td>';
current++;
}
html += '</tr>';
}
}
table.html(html);
},
fillMinutes = function () {
var table = picker.widget.find('.timepicker .timepicker-minutes table'), html = '', current = 0, i, j;
table.parent().hide();
for (i = 0; i < 5; i++) {
html += '<tr>';
for (j = 0; j < 4; j += 1) {
html += '<td class="minute">' + padLeft(current.toString()) + '</td>';
current += 3;
}
html += '</tr>';
}
table.html(html);
},
fillSeconds = function () {
var table = picker.widget.find('.timepicker .timepicker-seconds table'), html = '', current = 0, i, j;
table.parent().hide();
for (i = 0; i < 5; i++) {
html += '<tr>';
for (j = 0; j < 4; j += 1) {
html += '<td class="second">' + padLeft(current.toString()) + '</td>';
current += 3;
}
html += '</tr>';
}
table.html(html);
},
fillTime = function () {
if (!picker.date) return;
var timeComponents = picker.widget.find('.timepicker span[data-time-component]'),
hour = picker.date.hours(),
period = 'AM';
if (!picker.options.use24hours) {
if (hour >= 12) period = 'PM';
if (hour === 0) hour = 12;
else if (hour != 12) hour = hour % 12;
picker.widget.find('.timepicker [data-action=togglePeriod]').text(period);
}
timeComponents.filter('[data-time-component=hours]').text(padLeft(hour));
timeComponents.filter('[data-time-component=minutes]').text(padLeft(picker.date.minutes()));
timeComponents.filter('[data-time-component=seconds]').text(padLeft(picker.date.second()));
},
click = function (e) {
e.stopPropagation();
e.preventDefault();
picker.unset = false;
var target = $(e.target).closest('span, td, th'), month, year, step, day, oldDate = pMoment(picker.date);
if (target.length === 1) {
if (!target.is('.disabled')) {
switch (target[0].nodeName.toLowerCase()) {
case 'th':
switch (target[0].className) {
case 'switch':
showMode(1);
break;
case 'prev':
case 'next':
step = dpGlobal.modes[picker.viewMode].navStep;
if (target[0].className === 'prev') step = step * -1;
picker.viewDate.add(step, dpGlobal.modes[picker.viewMode].navFnc);
fillDate();
break;
}
break;
case 'span':
if (target.is('.month')) {
month = target.parent().find('span').index(target);
picker.viewDate.month(month);
} else {
year = parseInt(target.text(), 10) || 0;
picker.viewDate.year(year);
}
if (picker.viewMode !== 0) {
picker.date = pMoment({
y: picker.viewDate.year(),
M: picker.viewDate.month(),
d: picker.viewDate.date(),
h: picker.date.hours(),
m: picker.date.minutes()
});
notifyChange(oldDate, e.type);
}
showMode(-1);
fillDate();
break;
case 'td':
if (target.is('.day')) {
day = parseInt(target.text(), 10) || 1;
month = picker.viewDate.month();
year = picker.viewDate.year();
if (target.is('.old')) {
if (month === 0) {
month = 11;
year -= 1;
} else {
month -= 1;
}
} else if (target.is('.new')) {
if (month == 11) {
month = 0;
year += 1;
} else {
month += 1;
}
}
picker.date = pMoment({
y: year,
M: month,
d: day,
h: picker.date.hours(),
m: picker.date.minutes()
}
);
picker.viewDate = pMoment({
y: year, M: month, d: Math.min(28, day)
});
fillDate();
set();
notifyChange(oldDate, e.type);
}
break;
}
}
}
},
actions = {
incrementHours: function () {
checkDate("add", "hours", 1);
},
incrementMinutes: function () {
checkDate("add", "minutes", picker.options.minuteStepping);
},
incrementSeconds: function () {
checkDate("add", "seconds", 1);
},
decrementHours: function () {
checkDate("subtract", "hours", 1);
},
decrementMinutes: function () {
checkDate("subtract", "minutes", picker.options.minuteStepping);
},
decrementSeconds: function () {
checkDate("subtract", "seconds", 1);
},
togglePeriod: function () {
var hour = picker.date.hours();
if (hour >= 12) hour -= 12;
else hour += 12;
picker.date.hours(hour);
},
showPicker: function () {
picker.widget.find('.timepicker > div:not(.timepicker-picker)').hide();
picker.widget.find('.timepicker .timepicker-picker').show();
},
showHours: function () {
picker.widget.find('.timepicker .timepicker-picker').hide();
picker.widget.find('.timepicker .timepicker-hours').show();
},
showMinutes: function () {
picker.widget.find('.timepicker .timepicker-picker').hide();
picker.widget.find('.timepicker .timepicker-minutes').show();
},
showSeconds: function () {
picker.widget.find('.timepicker .timepicker-picker').hide();
picker.widget.find('.timepicker .timepicker-seconds').show();
},
selectHour: function (e) {
picker.date.hours(parseInt($(e.target).text(), 10));
actions.showPicker.call(picker);
},
selectMinute: function (e) {
picker.date.minutes(parseInt($(e.target).text(), 10));
actions.showPicker.call(picker);
},
selectSecond: function (e) {
picker.date.seconds(parseInt($(e.target).text(), 10));
actions.showPicker.call(picker);
}
},
doAction = function (e) {
var oldDate = pMoment(picker.date), action = $(e.currentTarget).data('action'), rv = actions[action].apply(picker, arguments);
stopEvent(e);
if (!picker.date) picker.date = pMoment({ y: 1970 });
set();
fillTime();
notifyChange(oldDate, e.type);
return rv;
},
stopEvent = function (e) {
e.stopPropagation();
e.preventDefault();
},
change = function (e) {
pMoment.lang(picker.options.language);
var input = $(e.target), oldDate = pMoment(picker.date), d = pMoment(input.val(), picker.format, picker.options.useStrict);
if (d.isValid()) {
update();
picker.setValue(d);
notifyChange(oldDate, e.type);
set();
}
else {
picker.viewDate = oldDate;
//picker.setValue(""); // unset the date when the input is erased
notifyChange(oldDate, e.type);
notifyError(d);
picker.unset = true;
input.val('');
}
},
showMode = function (dir) {
if (dir) {
picker.viewMode = Math.max(picker.minViewMode, Math.min(2, picker.viewMode + dir));
}
picker.widget.find('.datepicker > div').hide().filter('.datepicker-' + dpGlobal.modes[picker.viewMode].clsName).show();
},
attachDatePickerEvents = function () {
var $this, $parent, expanded, closed, collapseData;
picker.widget.on('click', '.datepicker *', $.proxy(click, this)); // this handles date picker clicks
picker.widget.on('click', '[data-action]', $.proxy(doAction, this)); // this handles time picker clicks
picker.widget.on('mousedown', $.proxy(stopEvent, this));
if (picker.options.pickDate && picker.options.pickTime) {
picker.widget.on('click.togglePicker', '.accordion-toggle', function (e) {
e.stopPropagation();
$this = $(this);
$parent = $this.closest('ul');
expanded = $parent.find('.in');
closed = $parent.find('.collapse:not(.in)');
if (expanded && expanded.length) {
collapseData = expanded.data('collapse');
if (collapseData && collapseData.transitioning) return;
expanded.collapse('hide');
closed.collapse('show');
$this.find('span').toggleClass(picker.options.icons.time + ' ' + picker.options.icons.date);
picker.element.find('.input-group-addon span').toggleClass(picker.options.icons.time + ' ' + picker.options.icons.date);
}
});
}
if (picker.isInput) {
picker.element.on({
'focus': $.proxy(picker.show, this),
'change': $.proxy(change, this),
'blur': $.proxy(picker.hide, this)
});
} else {
picker.element.on({
'change': $.proxy(change, this)
}, 'input');
if (picker.component) {
picker.component.on('click', $.proxy(picker.show, this));
} else {
picker.element.on('click', $.proxy(picker.show, this));
}
}
},
attachDatePickerGlobalEvents = function () {
$(window).on(
'resize.datetimepicker' + picker.id, $.proxy(place, this));
if (!picker.isInput) {
$(document).on(
'mousedown.datetimepicker' + picker.id, $.proxy(picker.hide, this));
}
},
detachDatePickerEvents = function () {
picker.widget.off('click', '.datepicker *', picker.click);
picker.widget.off('click', '[data-action]');
picker.widget.off('mousedown', picker.stopEvent);
if (picker.options.pickDate && picker.options.pickTime) {
picker.widget.off('click.togglePicker');
}
if (picker.isInput) {
picker.element.off({
'focus': picker.show,
'change': picker.change
});
} else {
picker.element.off({
'change': picker.change
}, 'input');
if (picker.component) {
picker.component.off('click', picker.show);
} else {
picker.element.off('click', picker.show);
}
}
},
detachDatePickerGlobalEvents = function () {
$(window).off('resize.datetimepicker' + picker.id);
if (!picker.isInput) {
$(document).off('mousedown.datetimepicker' + picker.id);
}
},
isInFixed = function () {
if (picker.element) {
var parents = picker.element.parents(), inFixed = false, i;
for (i = 0; i < parents.length; i++) {
if ($(parents[i]).css('position') == 'fixed') {
inFixed = true;
break;
}
}
;
return inFixed;
} else {
return false;
}
},
set = function () {
pMoment.lang(picker.options.language);
var formatted = '', input;
if (!picker.unset) formatted = pMoment(picker.date).format(picker.format);
if (!picker.isInput) {
if (picker.component) {
input = picker.element.find('input');
input.val(formatted);
}
picker.element.data('date', formatted);
} else {
picker.element.val(formatted);
}
if (!picker.options.pickTime) picker.hide();
},
checkDate = function (direction, unit, amount) {
pMoment.lang(picker.options.language);
var newDate;
if (direction == "add") {
newDate = pMoment(picker.date);
if (newDate.hours() == 23) newDate.add(amount, unit);
newDate.add(amount, unit);
}
else {
newDate = pMoment(picker.date).subtract(amount, unit);
}
if (newDate.isAfter(picker.options.endDate) || pMoment(newDate.subtract(amount, unit)).isBefore(picker.options.startDate) || isInDisableDates(newDate)) {
notifyError(newDate.format(picker.format));
return;
}
if (direction == "add") {
picker.date.add(amount, unit);
}
else {
picker.date.subtract(amount, unit);
}
},
isInDisableDates = function (date) {
pMoment.lang(picker.options.language);
var disabled = picker.options.disabledDates, i;
for (i in disabled) {
if (disabled[i] == pMoment(date).format("L")) {
return true;
}
}
return false;
},
isInEnableDates = function (date) {
pMoment.lang(picker.options.language);
var enabled = picker.options.enabledDates, i;
if (enabled.length) {
for (i in enabled) {
if (enabled[i] == pMoment(date).format("L")) {
return true;
}
}
return false;
}
return enabled === false ? true : false;
},
padLeft = function (string) {
string = string.toString();
if (string.length >= 2) return string;
else return '0' + string;
},
getTemplate = function (pickDate, pickTime, collapse) {
if (pickDate && pickTime) {
return (
'<div class="bootstrap-datetimepicker-widget dropdown-menu" style="z-index:9999 !important;">' +
'<ul class="list-unstyled">' +
'<li' + (collapse ? ' class="collapse in"' : '') + '>' +
'<div class="datepicker">' + dpGlobal.template + '</div>' +
'</li>' +
'<li class="picker-switch accordion-toggle"><a class="btn" style="width:100%"><span class="' + picker.options.icons.time + '"></span></a></li>' +
'<li' + (collapse ? ' class="collapse"' : '') + '>' +
'<div class="timepicker">' + tpGlobal.getTemplate() + '</div>' +
'</li>' +
'</ul>' +
'</div>'
);
} else if (pickTime) {
return (
'<div class="bootstrap-datetimepicker-widget dropdown-menu">' +
'<div class="timepicker">' + tpGlobal.getTemplate() + '</div>' +
'</div>'
);
} else {
return (
'<div class="bootstrap-datetimepicker-widget dropdown-menu">' +
'<div class="datepicker">' + dpGlobal.template + '</div>' +
'</div>'
);
}
},
dpGlobal = {
modes: [
{
clsName: 'days',
navFnc: 'month',
navStep: 1
},
{
clsName: 'months',
navFnc: 'year',
navStep: 1
},
{
clsName: 'years',
navFnc: 'year',
navStep: 10
}],
headTemplate:
'<thead>' +
'<tr>' +
'<th class="prev">&lsaquo;</th><th colspan="5" class="switch"></th><th class="next">&rsaquo;</th>' +
'</tr>' +
'</thead>',
contTemplate:
'<tbody><tr><td colspan="7"></td></tr></tbody>'
},
tpGlobal = {
hourTemplate: '<span data-action="showHours" data-time-component="hours" class="timepicker-hour"></span>',
minuteTemplate: '<span data-action="showMinutes" data-time-component="minutes" class="timepicker-minute"></span>',
secondTemplate: '<span data-action="showSeconds" data-time-component="seconds" class="timepicker-second"></span>'
};
dpGlobal.template =
'<div class="datepicker-days">' +
'<table class="table-condensed">' + dpGlobal.headTemplate + '<tbody></tbody></table>' +
'</div>' +
'<div class="datepicker-months">' +
'<table class="table-condensed">' + dpGlobal.headTemplate + dpGlobal.contTemplate + '</table>' +
'</div>' +
'<div class="datepicker-years">' +
'<table class="table-condensed">' + dpGlobal.headTemplate + dpGlobal.contTemplate + '</table>' +
'</div>';
tpGlobal.getTemplate = function () {
return (
'<div class="timepicker-picker">' +
'<table class="table-condensed">' +
'<tr>' +
'<td><a href="#" class="btn" data-action="incrementHours"><span class="' + picker.options.icons.up + '"></span></a></td>' +
'<td class="separator"></td>' +
'<td>' + (picker.options.useMinutes ? '<a href="#" class="btn" data-action="incrementMinutes"><span class="' + picker.options.icons.up + '"></span></a>' : '') + '</td>' +
(picker.options.useSeconds ?
'<td class="separator"></td><td><a href="#" class="btn" data-action="incrementSeconds"><span class="' + picker.options.icons.up + '"></span></a></td>' : '') +
(picker.options.use24hours ? '' : '<td class="separator"></td>') +
'</tr>' +
'<tr>' +
'<td>' + tpGlobal.hourTemplate + '</td> ' +
'<td class="separator">:</td>' +
'<td>' + (picker.options.useMinutes ? tpGlobal.minuteTemplate : '<span class="timepicker-minute">00</span>') + '</td> ' +
(picker.options.useSeconds ?
'<td class="separator">:</td><td>' + tpGlobal.secondTemplate + '</td>' : '') +
(picker.options.use24hours ? '' : '<td class="separator"></td>' +
'<td><button type="button" class="btn btn-primary" data-action="togglePeriod"></button></td>') +
'</tr>' +
'<tr>' +
'<td><a href="#" class="btn" data-action="decrementHours"><span class="' + picker.options.icons.down + '"></span></a></td>' +
'<td class="separator"></td>' +
'<td>' + (picker.options.useMinutes ? '<a href="#" class="btn" data-action="decrementMinutes"><span class="' + picker.options.icons.down + '"></span></a>' : '') + '</td>' +
(picker.options.useSeconds ?
'<td class="separator"></td><td><a href="#" class="btn" data-action="decrementSeconds"><span class="' + picker.options.icons.down + '"></span></a></td>' : '') +
(picker.options.use24hours ? '' : '<td class="separator"></td>') +
'</tr>' +
'</table>' +
'</div>' +
'<div class="timepicker-hours" data-action="selectHour">' +
'<table class="table-condensed"></table>' +
'</div>' +
'<div class="timepicker-minutes" data-action="selectMinute">' +
'<table class="table-condensed"></table>' +
'</div>' +
(picker.options.useSeconds ?
'<div class="timepicker-seconds" data-action="selectSecond"><table class="table-condensed"></table></div>' : '')
);
};
picker.destroy = function () {
detachDatePickerEvents();
detachDatePickerGlobalEvents();
picker.widget.remove();
picker.element.removeData('DateTimePicker');
if (picker.component)
picker.component.removeData('DateTimePicker');
};
picker.show = function (e) {
picker.widget.show();
picker.height = picker.component ? picker.component.outerHeight() : picker.element.outerHeight();
place();
picker.element.trigger({
type: 'show.dp',
date: pMoment(picker.date)
});
attachDatePickerGlobalEvents();
if (e) {
stopEvent(e);
}
},
picker.disable = function () {
var input = picker.element.find('input');
if(!input.prop('disabled')) return;
input.prop('disabled', true);
detachDatePickerEvents();
},
picker.enable = function () {
var input = picker.element.find('input');
if(!input.prop('disabled')) return;
input.prop('disabled', true);
attachDatePickerEvents();
},
picker.hide = function (event) {
if (event && $(event.target).is(picker.element.attr("id")))
return;
// Ignore event if in the middle of a picker transition
var collapse = picker.widget.find('.collapse'), i, collapseData;
for (i = 0; i < collapse.length; i++) {
collapseData = collapse.eq(i).data('collapse');
if (collapseData && collapseData.transitioning)
return;
}
picker.widget.hide();
picker.viewMode = picker.startViewMode;
showMode();
picker.element.trigger({
type: 'hide.dp',
date: pMoment(picker.date)
});
detachDatePickerGlobalEvents();
},
picker.setValue = function (newDate) {
pMoment.lang(picker.options.language);
if (!newDate) {
picker.unset = true;
} else {
picker.unset = false;
}
if (!pMoment.isMoment(newDate)) newDate = pMoment(newDate);
if (newDate.isValid()) {
picker.date = newDate;
set();
picker.viewDate = pMoment({ y: picker.date.year(), M: picker.date.month() });
fillDate();
fillTime();
}
else {
notifyError(newDate);
}
},
picker.getDate = function () {
if (picker.unset) return null;
return picker.date;
},
picker.setDate = function (date) {
date = pMoment(date);
if (!date) picker.setValue(null);
else picker.setValue(date);
},
picker.setEnabledDates = function (dates) {
if (!dates) picker.options.enabledDates = false;
else picker.options.enabledDates = dates;
if (picker.viewDate) update();
},
picker.setEndDate = function (date) {
picker.options.endDate = pMoment(date);
if (!picker.options.endDate.isValid()) {
picker.options.endDate = pMoment().add(50, "y");
}
if (picker.viewDate) update();
},
picker.setStartDate = function (date) {
picker.options.startDate = pMoment(date);
if (!picker.options.startDate.isValid()) {
picker.options.startDate = pMoment({ y: 1970 });
}
if (picker.viewDate) update();
};
init();
};
$.fn.datetimepicker = function (options) {
return this.each(function () {
var $this = $(this), data = $this.data('DateTimePicker');
if (!data) $this.data('DateTimePicker', new DateTimePicker(this, options));
});
};
}));
<!-- required CSS Files -->
<link href="views/css/bootstrap_3/bootstrap.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="views/css/bootstrap_3/date-picker/daterangepicker.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="views/css/bootstrap_3/date-picker/datetimepicker.css" rel="stylesheet" type="text/css" media="screen"/>
<!-- required JS libraries -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="views/js/bootstrap_3/bootstrap.min.js"></script>
<script type="text/javascript" src="views/js/bootstrap_3/date-picker/moment.min.js"></script>
<script type="text/javascript" src="views/js/bootstrap_3/date-picker/daterangepicker.js"></script>
<div class="btn-toolbar" role="toolbar">
<div class="btn-group date-range-item" id="date-day">
<button type="button" class="btn btn-default prev small-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
<button type="button" class="btn btn-default date-val">October 20, 2013</button>
<button type="button" class="btn btn-default next small-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
<div class="btn-group date-range-item" id="date-week">
<button type="button" class="btn btn-default prev small-btn"><span class="glyphicon glyphicon-chevron-left"></span></button>
<button type="button" class="btn btn-default week-val">
<span class="st_week">October 20, 2013</span>
-
<span class="en_week">October 20, 2013</span>
</button>
<button type="button" class="btn btn-default next small-btn"><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
<div class="btn-group date-range-item" id="date-range">
<button type="button" class="btn btn-default" id="start_date">October 20, 2013</button>
<button type="button" class="btn btn-default date-separator small-btn">-</button>
<button type="button" class="btn btn-default" id="end_date">November 10, 2013</button>
</div>
<div class="btn-group">
<button type="button" id="reportrange" class="btn btn-default">&nbsp;<i class="glyphicon glyphicon-calendar icon-calendar icon-large"></i>&nbsp;</button>
</div>
<div class="btn-group custom-calendar-btn">
<button type="button" class="btn btn-default current" data-title="date-day">Day</button>
<button type="button" class="btn btn-default current" data-title="date-week">Week</button>
<button type="button" class="btn btn-default current" data-title="date-range">Date Range</button>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
CustomDate.dateSelector('#date-day', function(value){
//define your own call back functionality with return value
console.log('>> date-day: ', value);
});
CustomDate.weekSelector('#date-week', function(start, end){
//define your own call back functionality with return value
console.log('>> date-week: ', start, end);
});
CustomDate.dateRangeSelector('#date-range', function(start,end){
//define your own call back functionality with return value
console.log('>> date-range: ', start, end);
});
})
</script>
/*
Filename: Custom Date Manager
Dependency:
----------
1. jquery v1.10.2
2. Twitter Bootstrap3 Library: http://getbootstrap.com/
3. Moment.js: momentjs.com version : 2.4.0
Slightly modified libraries:
----------------------------
1. daterange picker: https://github.com/dangrossman/bootstrap-daterangepicker (attached file)
2. datetimepicker: http://eonasdan.github.io/bootstrap-datetimepicker (attached file)
*/
var CustomDate = {
$stOfWeek : '',
$enOfweek : '',
$date : '',
weekCounter : 0,
dayCounter : 0,
dateSelector: function(ele, callback){
var count = 0;
var $sel = $(ele);
this.$date = $sel.find('.date-val');
this.$date.datetimepicker({ pickTime: false }).on("change.dp",function (e) {
if (count == 0){
var val = moment(e.date).format('MMMM DD, YYYY');
this.$date.text(val);
(typeof callback === 'function' ) ? callback(val) : '';
count++;
}else{
count = 0;
}
}.bind(this));
$sel.find('.prev').unbind('click').on('click', function(){
this.dayCounter = -1;
this.changeDate(callback);
}.bind(this));
$sel.find('.next').unbind('click').on('click', function(){
this.dayCounter = 1;
this.changeDate(callback);
}.bind(this));
this.currentDate(callback);
},
currentDate:function(callback){
var val = moment().format('MMMM DD, YYYY')
this.$date.text(val);
(typeof callback === 'function' ) ? callback(val) : '';
},
changeDate: function(callback){
var val = moment(this.$date.text()).add('day', this.dayCounter).format('MMMM DD, YYYY')
this.$date.text(val);
(typeof callback === 'function' ) ? callback(val) : '';
},
weekSelector: function(ele, callback){
var $sel = $(ele);
var count = 0;
this.$stOfWeek = $sel.find('.st_week');
this.$enOfweek = $sel.find('.en_week');
this.$weekdate = $sel.find('.week-val');
this.$weekdate.datetimepicker({ pickTime: false }).on("change.dp",function (e) {
if (count == 0){
var st = moment(moment(e.date).format('MMMM DD, YYYY')).startOf('week').format('MMMM DD, YYYY');
var en = moment(moment(e.date).format('MMMM DD, YYYY')).endOf('week').format('MMMM DD, YYYY');
this.setWeek(st,en);
(typeof callback === 'function' ) ? callback(st,en) : '';
count++;
}else{
count = 0;
}
}.bind(this));
$sel.find('.prev').on('click', function(){
this.weekCounter = -1;
this.changeWeek(callback);
}.bind(this));
$sel.find('.next').on('click', function(){
this.weekCounter = 1;
this.changeWeek(callback);
}.bind(this));
this.currentWeek(callback);
},
currentWeek: function(){
var st = moment().startOf('week').format('MMMM DD, YYYY');
var en = moment().endOf('week').format('MMMM DD, YYYY');
this.setWeek(st, en);
},
changeWeek: function(callback) {
var st = moment(this.$stOfWeek.text()).add('week', this.weekCounter).startOf('week').format('MMMM DD, YYYY');
var en = moment(this.$stOfWeek.text()).add('week', this.weekCounter).endOf('week').format('MMMM DD, YYYY');
this.setWeek(st, en);
(typeof callback === 'function' ) ? callback(st,en) : '';
},
setWeek: function(st, en){
this.$stOfWeek.text(st);
this.$enOfweek.text(en);
},
dateRangeSelector: function(ele, callback){
var $sel = $(ele);
$sel.find("#start_date").text(moment().startOf('month').format('MMMM DD, YYYY'));
$sel.find("#end_date").text(moment().endOf('month').format('MMMM DD, YYYY'));
$sel.find('.date-separator').daterangepicker({
applyClass: 'btn-primary',
startDate: moment().subtract('days', 29),
endDate: moment(),
opens: "left"
}, function(start, end) {
$sel.find("#start_date").html(start.format('MMMM DD, YYYY'));
$sel.find("#end_date").html(end.format('MMMM DD, YYYY'));
(typeof callback === 'function' ) ? callback( start.format('MMMM DD, YYYY'), end.format('MMMM DD, YYYY')) : '';
}
);
$sel.find("#end_date, #start_date").on('click', function(){
$sel.find('.date-separator').click();
});
}
}
/**
* @version: 1.2
* @author: Dan Grossman http://www.dangrossman.info/
* @date: 2013-07-25
* @copyright: Copyright (c) 2012-2013 Dan Grossman. All rights reserved.
* @license: Licensed under Apache License v2.0. See http://www.apache.org/licenses/LICENSE-2.0
* @website: http://www.improvely.com/
*
* changes by masud <masudiiuc@gmail.com>
* ---------------------------------------
* 1. Custom Range -> Date Range
* 2. $(".custom-calendar-btn") is added for Button group
* 3. clickRange() function is modified a bit
*
*/
!function ($) {
var DateRangePicker = function (element, options, cb) {
var hasOptions = typeof options == 'object';
var localeObject;
//option defaults
this.startDate = moment().startOf('day');
this.endDate = moment().startOf('day');
this.minDate = false;
this.maxDate = false;
this.dateLimit = false;
this.showDropdowns = false;
this.showWeekNumbers = false;
this.timePicker = false;
this.timePickerIncrement = 30;
this.timePicker12Hour = true;
this.ranges = {};
this.opens = 'right';
this.buttonClasses = ['btn', 'btn-small'];
this.applyClass = 'btn-success';
this.cancelClass = 'btn-default';
this.format = 'MM/DD/YYYY';
this.separator = ' - ';
this.locale = {
applyLabel: 'Apply',
cancelLabel: 'Cancel',
fromLabel: 'From',
toLabel: 'To',
weekLabel: 'W',
customRangeLabel: 'Date Range',
daysOfWeek: moment()._lang._weekdaysMin.slice(),
monthNames: moment()._lang._monthsShort.slice(),
firstDay: 0
};
this.cb = function () { };
// by default, the daterangepicker element is placed at the bottom of HTML body
this.parentEl = 'body';
//element that triggered the date range picker
this.element = $(element);
if (this.element.hasClass('pull-right'))
this.opens = 'left';
if (this.element.is('input')) {
this.element.on({
click: $.proxy(this.show, this),
focus: $.proxy(this.show, this)
});
} else {
this.element.on('click', $.proxy(this.show, this));
}
localeObject = this.locale;
if (hasOptions) {
if (typeof options.locale == 'object') {
$.each(localeObject, function (property, value) {
localeObject[property] = options.locale[property] || value;
});
}
if (options.applyClass) {
this.applyClass = options.applyClass;
}
if (options.cancelClass) {
this.cancelClass = options.cancelClass;
}
}
var DRPTemplate = '<div class="daterangepicker dropdown-menu">' +
'<div class="ranges">' +
'<div class="range_inputs">' +
'<div class="daterangepicker_start_input" style="float: left">' +
'<label for="daterangepicker_start">' + this.locale.fromLabel + '</label>' +
'<input class="input-mini" type="text" name="daterangepicker_start" value="" disabled="disabled" />' +
'</div>' +
'<div class="daterangepicker_end_input" style="float: left; padding-left: 11px">' +
'<label for="daterangepicker_end">' + this.locale.toLabel + '</label>' +
'<input class="input-mini" type="text" name="daterangepicker_end" value="" disabled="disabled" />' +
'</div>' +
'<label class="pull-left date-heading">Pick a Date Range</label>'+
'<button class="pull-right ' + this.applyClass + ' applyBtn" disabled="disabled">' + this.locale.applyLabel + '</button>&nbsp;' +
//'<button class="' + this.cancelClass + ' cancelBtn">' + this.locale.cancelLabel + '</button>' +
'</div>' +
'</div>' +
'<div style="clear:both"></div>'+
'<div class="calendar left"></div>' +
'<div class="calendar right"></div>' +
'</div>';
this.parentEl = (hasOptions && options.parentEl && $(options.parentEl)) || $(this.parentEl);
//the date range picker
this.container = $(DRPTemplate).appendTo(this.parentEl);
if (hasOptions) {
if (typeof options.format == 'string')
this.format = options.format;
if (typeof options.separator == 'string')
this.separator = options.separator;
if (typeof options.startDate == 'string')
this.startDate = moment(options.startDate, this.format);
if (typeof options.endDate == 'string')
this.endDate = moment(options.endDate, this.format);
if (typeof options.minDate == 'string')
this.minDate = moment(options.minDate, this.format);
if (typeof options.maxDate == 'string')
this.maxDate = moment(options.maxDate, this.format);
if (typeof options.startDate == 'object')
this.startDate = moment(options.startDate);
if (typeof options.endDate == 'object')
this.endDate = moment(options.endDate);
if (typeof options.minDate == 'object')
this.minDate = moment(options.minDate);
if (typeof options.maxDate == 'object')
this.maxDate = moment(options.maxDate);
if (typeof options.ranges == 'object') {
for (var range in options.ranges) {
var start = moment(options.ranges[range][0]);
var end = moment(options.ranges[range][1]);
// If we have a min/max date set, bound this range
// to it, but only if it would otherwise fall
// outside of the min/max.
if (this.minDate && start.isBefore(this.minDate))
start = moment(this.minDate);
if (this.maxDate && end.isAfter(this.maxDate))
end = moment(this.maxDate);
// If the end of the range is before the minimum (if min is set) OR
// the start of the range is after the max (also if set) don't display this
// range option.
if ((this.minDate && end.isBefore(this.minDate)) || (this.maxDate && start.isAfter(this.maxDate))) {
continue;
}
this.ranges[range] = [start, end];
}
var list = '<ul>';
for (var range in this.ranges) {
list += '<li>' + range + '</li>';
}
list += '<li>' + this.locale.customRangeLabel + '</li>';
list += '</ul>';
this.container.find('.ranges').prepend(list);
}
if (typeof options.dateLimit == 'object')
this.dateLimit = options.dateLimit;
// update day names order to firstDay
if (typeof options.locale == 'object') {
if (typeof options.locale.firstDay == 'number') {
this.locale.firstDay = options.locale.firstDay;
var iterator = options.locale.firstDay;
while (iterator > 0) {
this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift());
iterator--;
}
}
}
if (typeof options.opens == 'string')
this.opens = options.opens;
if (typeof options.showWeekNumbers == 'boolean') {
this.showWeekNumbers = options.showWeekNumbers;
}
if (typeof options.buttonClasses == 'string') {
this.buttonClasses = [options.buttonClasses];
}
if (typeof options.buttonClasses == 'object') {
this.buttonClasses = options.buttonClasses;
}
if (typeof options.showDropdowns == 'boolean') {
this.showDropdowns = options.showDropdowns;
}
if (typeof options.timePicker == 'boolean') {
this.timePicker = options.timePicker;
}
if (typeof options.timePickerIncrement == 'number') {
this.timePickerIncrement = options.timePickerIncrement;
}
if (typeof options.timePicker12Hour == 'boolean') {
this.timePicker12Hour = options.timePicker12Hour;
}
}
if (!this.timePicker) {
this.startDate = this.startDate.startOf('day');
this.endDate = this.endDate.startOf('day');
}
//apply CSS classes to buttons
var c = this.container;
$.each(this.buttonClasses, function (idx, val) {
c.find('button').addClass(val);
});
if (this.opens == 'right') {
//swap calendar positions
var left = this.container.find('.calendar.left');
var right = this.container.find('.calendar.right');
left.removeClass('left').addClass('right');
right.removeClass('right').addClass('left');
}
if (typeof options == 'undefined' || typeof options.ranges == 'undefined') {
this.container.find('.calendar').show();
this.move();
}
if (typeof cb == 'function')
this.cb = cb;
this.container.addClass('opens' + this.opens);
//try parse date if in text input
if (!hasOptions || (typeof options.startDate == 'undefined' && typeof options.endDate == 'undefined')) {
if ($(this.element).is('input[type=text]')) {
var val = $(this.element).val();
var split = val.split(this.separator);
var start, end;
if (split.length == 2) {
start = moment(split[0], this.format);
end = moment(split[1], this.format);
}
if (start != null && end != null) {
this.startDate = start;
this.endDate = end;
}
}
}
//state
this.oldStartDate = this.startDate.clone();
this.oldEndDate = this.endDate.clone();
this.leftCalendar = {
month: moment([this.startDate.year(), this.startDate.month(), 1, this.startDate.hour(), this.startDate.minute()]),
calendar: []
};
this.rightCalendar = {
month: moment([this.endDate.year(), this.endDate.month(), 1, this.endDate.hour(), this.endDate.minute()]),
calendar: []
};
//event listeners
this.container.on('mousedown', $.proxy(this.mousedown, this));
this.container.find('.calendar')
.on('click', '.prev', $.proxy(this.clickPrev, this))
.on('click', '.next', $.proxy(this.clickNext, this))
.on('click', 'td.available', $.proxy(this.clickDate, this))
.on('mouseenter', 'td.available', $.proxy(this.enterDate, this))
.on('mouseleave', 'td.available', $.proxy(this.updateFormInputs, this))
.on('change', 'select.yearselect', $.proxy(this.updateMonthYear, this))
.on('change', 'select.monthselect', $.proxy(this.updateMonthYear, this))
.on('change', 'select.hourselect,select.minuteselect,select.ampmselect', $.proxy(this.updateTime, this));
this.container.find('.ranges')
.on('click', 'button.applyBtn', $.proxy(this.clickApply, this))
.on('click', 'button.cancelBtn', $.proxy(this.clickCancel, this))
.on('click', '.daterangepicker_start_input,.daterangepicker_end_input', $.proxy(this.showCalendars, this))
.on('click', 'li', $.proxy(this.clickRange, this))
.on('mouseenter', 'li', $.proxy(this.enterRange, this))
.on('mouseleave', 'li', $.proxy(this.updateFormInputs, this));
/*button group*/
$(".custom-calendar-btn").on('click', 'button.range', $.proxy(this.clickRange, this));
this.element.on('keyup', $.proxy(this.updateFromControl, this));
this.updateView();
this.updateCalendars();
};
DateRangePicker.prototype = {
constructor: DateRangePicker,
mousedown: function (e) {
e.stopPropagation();
},
updateView: function () {
this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year());
this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year());
this.updateFormInputs();
},
updateFormInputs: function () {
this.container.find('input[name=daterangepicker_start]').val(this.startDate.format(this.format));
this.container.find('input[name=daterangepicker_end]').val(this.endDate.format(this.format));
if (this.startDate.isSame(this.endDate) || this.startDate.isBefore(this.endDate)) {
this.container.find('button.applyBtn').removeAttr('disabled');
} else {
this.container.find('button.applyBtn').attr('disabled', 'disabled');
}
},
updateFromControl: function () {
if (!this.element.is('input')) return;
if (!this.element.val().length) return;
var dateString = this.element.val().split(this.separator);
var start = moment(dateString[0], this.format);
var end = moment(dateString[1], this.format);
if (start == null || end == null) return;
if (end.isBefore(start)) return;
this.oldStartDate = this.startDate.clone();
this.oldEndDate = this.endDate.clone();
this.startDate = start;
this.endDate = end;
if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
this.notify();
this.updateCalendars();
},
notify: function () {
this.updateView();
this.cb(this.startDate, this.endDate);
},
move: function () {
var parentOffset = {
top: this.parentEl.offset().top - (this.parentEl.is('body') ? 0 : this.parentEl.scrollTop()),
left: this.parentEl.offset().left - (this.parentEl.is('body') ? 0 : this.parentEl.scrollLeft())
};
if (this.opens == 'left') {
this.container.css({
top: this.element.offset().top + this.element.outerHeight() - parentOffset.top,
right: $(window).width() - this.element.offset().left - this.element.outerWidth() - parentOffset.left,
left: 'auto'
});
if (this.container.offset().left < 0) {
this.container.css({
right: 'auto',
left: 9
});
}
} else {
this.container.css({
top: this.element.offset().top + this.element.outerHeight() - parentOffset.top,
left: this.element.offset().left - parentOffset.left,
right: 'auto'
});
if (this.container.offset().left + this.container.outerWidth() > $(window).width()) {
this.container.css({
left: 'auto',
right: 0
});
}
}
},
show: function (e) {
this.container.show();
this.move();
if (e) {
e.stopPropagation();
e.preventDefault();
}
$(document).on('mousedown', $.proxy(this.hide, this));
this.element.trigger('shown', {target: e.target, picker: this});
},
hide: function (e) {
this.container.hide();
if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
this.notify();
this.oldStartDate = this.startDate.clone();
this.oldEndDate = this.endDate.clone();
$(document).off('mousedown', this.hide);
this.element.trigger('hidden', { picker: this });
},
enterRange: function (e) {
var label = e.target.innerHTML;
if (label == this.locale.customRangeLabel) {
this.updateView();
} else {
var dates = this.ranges[label];
this.container.find('input[name=daterangepicker_start]').val(dates[0].format(this.format));
this.container.find('input[name=daterangepicker_end]').val(dates[1].format(this.format));
}
},
showCalendars: function() {
this.container.find('.calendar').show();
this.move();
},
updateInputText: function() {
if (this.element.is('input'))
this.element.val(this.startDate.format(this.format) + this.separator + this.endDate.format(this.format));
},
clickRange: function (e) {
var label = e.target.innerHTML;
if (label == this.locale.customRangeLabel) {
/** if calendar box is not opend, then the click events opens that
* masud<masudiiuc@staff.com>
*/
this.element.click();
this.showCalendars();
} else {
var dates = this.ranges[label];
this.startDate = dates[0];
this.endDate = dates[1];
if (!this.timePicker) {
this.startDate.startOf('day');
this.endDate.startOf('day');
}
this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year()).hour(this.startDate.hour()).minute(this.startDate.minute());
this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year()).hour(this.endDate.hour()).minute(this.endDate.minute());
this.updateCalendars();
this.updateInputText();
this.container.find('.calendar').hide();
this.hide();
}
},
clickPrev: function (e) {
var cal = $(e.target).parents('.calendar');
if (cal.hasClass('left')) {
this.leftCalendar.month.subtract('month', 1);
} else {
this.rightCalendar.month.subtract('month', 1);
}
this.updateCalendars();
},
clickNext: function (e) {
var cal = $(e.target).parents('.calendar');
if (cal.hasClass('left')) {
this.leftCalendar.month.add('month', 1);
} else {
this.rightCalendar.month.add('month', 1);
}
this.updateCalendars();
},
enterDate: function (e) {
var title = $(e.target).attr('data-title');
var row = title.substr(1, 1);
var col = title.substr(3, 1);
var cal = $(e.target).parents('.calendar');
if (cal.hasClass('left')) {
this.container.find('input[name=daterangepicker_start]').val(this.leftCalendar.calendar[row][col].format(this.format));
} else {
this.container.find('input[name=daterangepicker_end]').val(this.rightCalendar.calendar[row][col].format(this.format));
}
},
clickDate: function (e) {
var title = $(e.target).attr('data-title');
var row = title.substr(1, 1);
var col = title.substr(3, 1);
var cal = $(e.target).parents('.calendar');
if (cal.hasClass('left')) {
var startDate = this.leftCalendar.calendar[row][col];
var endDate = this.endDate;
if (typeof this.dateLimit == 'object') {
var maxDate = moment(startDate).add(this.dateLimit).startOf('day');
if (endDate.isAfter(maxDate)) {
endDate = maxDate;
}
}
} else {
var startDate = this.startDate;
var endDate = this.rightCalendar.calendar[row][col];
if (typeof this.dateLimit == 'object') {
var minDate = moment(endDate).subtract(this.dateLimit).startOf('day');
if (startDate.isBefore(minDate)) {
startDate = minDate;
}
}
}
cal.find('td').removeClass('active');
if (startDate.isSame(endDate) || startDate.isBefore(endDate)) {
$(e.target).addClass('active');
this.startDate = startDate;
this.endDate = endDate;
} else if (startDate.isAfter(endDate)) {
$(e.target).addClass('active');
this.startDate = startDate;
this.endDate = moment(startDate).add('day', 1).startOf('day');
}
this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year());
this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year());
this.updateCalendars();
},
clickApply: function (e) {
this.updateInputText();
this.hide();
},
clickCancel: function (e) {
this.startDate = this.oldStartDate;
this.endDate = this.oldEndDate;
this.updateView();
this.updateCalendars();
this.hide();
},
updateMonthYear: function (e) {
var isLeft = $(e.target).closest('.calendar').hasClass('left');
var cal = this.container.find('.calendar.left');
if (!isLeft)
cal = this.container.find('.calendar.right');
// Month must be Number for new moment versions
var month = parseInt(cal.find('.monthselect').val(), 10);
var year = cal.find('.yearselect').val();
if (isLeft) {
this.leftCalendar.month.month(month).year(year);
} else {
this.rightCalendar.month.month(month).year(year);
}
this.updateCalendars();
},
updateTime: function(e) {
var isLeft = $(e.target).closest('.calendar').hasClass('left');
var cal = this.container.find('.calendar.left');
if (!isLeft)
cal = this.container.find('.calendar.right');
var hour = parseInt(cal.find('.hourselect').val());
var minute = parseInt(cal.find('.minuteselect').val());
if (this.timePicker12Hour) {
var ampm = cal.find('.ampmselect').val();
if (ampm == 'PM' && hour < 12)
hour += 12;
if (ampm == 'AM' && hour == 12)
hour = 0;
}
if (isLeft) {
var start = this.startDate.clone();
start.hour(hour);
start.minute(minute);
this.startDate = start;
this.leftCalendar.month.hour(hour).minute(minute);
} else {
var end = this.endDate.clone();
end.hour(hour);
end.minute(minute);
this.endDate = end;
this.rightCalendar.month.hour(hour).minute(minute);
}
this.updateCalendars();
},
updateCalendars: function () {
this.leftCalendar.calendar = this.buildCalendar(this.leftCalendar.month.month(), this.leftCalendar.month.year(), this.leftCalendar.month.hour(), this.leftCalendar.month.minute(), 'left');
this.rightCalendar.calendar = this.buildCalendar(this.rightCalendar.month.month(), this.rightCalendar.month.year(), this.rightCalendar.month.hour(), this.rightCalendar.month.minute(), 'right');
this.container.find('.calendar.left').html(this.renderCalendar(this.leftCalendar.calendar, this.startDate, this.minDate, this.maxDate));
this.container.find('.calendar.right').html(this.renderCalendar(this.rightCalendar.calendar, this.endDate, this.startDate, this.maxDate));
this.container.find('.ranges li').removeClass('active');
var customRange = true;
var i = 0;
for (var range in this.ranges) {
if (this.timePicker) {
if (this.startDate.isSame(this.ranges[range][0]) && this.endDate.isSame(this.ranges[range][1])) {
customRange = false;
this.container.find('.ranges li:eq(' + i + ')').addClass('active');
}
} else {
//ignore times when comparing dates if time picker is not enabled
if (this.startDate.format('YYYY-MM-DD') == this.ranges[range][0].format('YYYY-MM-DD') && this.endDate.format('YYYY-MM-DD') == this.ranges[range][1].format('YYYY-MM-DD')) {
customRange = false;
this.container.find('.ranges li:eq(' + i + ')').addClass('active');
}
}
i++;
}
if (customRange)
this.container.find('.ranges li:last').addClass('active');
},
buildCalendar: function (month, year, hour, minute, side) {
var firstDay = moment([year, month, 1]);
var lastMonth = moment(firstDay).subtract('month', 1).month();
var lastYear = moment(firstDay).subtract('month', 1).year();
var daysInLastMonth = moment([lastYear, lastMonth]).daysInMonth();
var dayOfWeek = firstDay.day();
//initialize a 6 rows x 7 columns array for the calendar
var calendar = [];
for (var i = 0; i < 6; i++) {
calendar[i] = [];
}
//populate the calendar with date objects
var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1;
if (startDay > daysInLastMonth)
startDay -= 7;
if (dayOfWeek == this.locale.firstDay)
startDay = daysInLastMonth - 6;
var curDate = moment([lastYear, lastMonth, startDay, 12, minute]);
for (var i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = moment(curDate).add('hour', 24)) {
if (i > 0 && col % 7 == 0) {
col = 0;
row++;
}
calendar[row][col] = curDate.clone().hour(hour);
curDate.hour(12);
}
return calendar;
},
renderDropdowns: function (selected, minDate, maxDate) {
var currentMonth = selected.month();
var monthHtml = '<select class="monthselect">';
var inMinYear = false;
var inMaxYear = false;
for (var m = 0; m < 12; m++) {
if ((!inMinYear || m >= minDate.month()) && (!inMaxYear || m <= maxDate.month())) {
monthHtml += "<option value='" + m + "'" +
(m === currentMonth ? " selected='selected'" : "") +
">" + this.locale.monthNames[m] + "</option>";
}
}
monthHtml += "</select>";
var currentYear = selected.year();
var maxYear = (maxDate && maxDate.year()) || (currentYear + 5);
var minYear = (minDate && minDate.year()) || (currentYear - 50);
var yearHtml = '<select class="yearselect">';
for (var y = minYear; y <= maxYear; y++) {
yearHtml += '<option value="' + y + '"' +
(y === currentYear ? ' selected="selected"' : '') +
'>' + y + '</option>';
}
yearHtml += '</select>';
return monthHtml + yearHtml;
},
renderCalendar: function (calendar, selected, minDate, maxDate) {
var html = '<div class="calendar-date">';
html += '<table class="table-condensed">';
html += '<thead>';
html += '<tr>';
// add empty cell for week number
if (this.showWeekNumbers)
html += '<th></th>';
if (!minDate || minDate.isBefore(calendar[1][1])) {
html += '<th class="prev available"><i class="icon-arrow-left glyphicon glyphicon-arrow-left"></i></th>';
} else {
html += '<th></th>';
}
var dateHtml = this.locale.monthNames[calendar[1][1].month()] + calendar[1][1].format(" YYYY");
if (this.showDropdowns) {
dateHtml = this.renderDropdowns(calendar[1][1], minDate, maxDate);
}
html += '<th colspan="5" style="width: auto">' + dateHtml + '</th>';
if (!maxDate || maxDate.isAfter(calendar[1][1])) {
html += '<th class="next available"><i class="icon-arrow-right glyphicon glyphicon-arrow-right"></i></th>';
} else {
html += '<th></th>';
}
html += '</tr>';
html += '<tr>';
// add week number label
if (this.showWeekNumbers)
html += '<th class="week">' + this.locale.weekLabel + '</th>';
$.each(this.locale.daysOfWeek, function (index, dayOfWeek) {
html += '<th>' + dayOfWeek + '</th>';
});
html += '</tr>';
html += '</thead>';
html += '<tbody>';
for (var row = 0; row < 6; row++) {
html += '<tr>';
// add week number
if (this.showWeekNumbers)
html += '<td class="week">' + calendar[row][0].week() + '</td>';
for (var col = 0; col < 7; col++) {
var cname = 'available ';
cname += (calendar[row][col].month() == calendar[1][1].month()) ? '' : 'off';
if ((minDate && calendar[row][col].isBefore(minDate)) || (maxDate && calendar[row][col].isAfter(maxDate))) {
cname = ' off disabled ';
} else if (calendar[row][col].format('YYYY-MM-DD') == selected.format('YYYY-MM-DD')) {
cname += ' active ';
if (calendar[row][col].format('YYYY-MM-DD') == this.startDate.format('YYYY-MM-DD')) {
cname += ' start-date ';
}
if (calendar[row][col].format('YYYY-MM-DD') == this.endDate.format('YYYY-MM-DD')) {
cname += ' end-date ';
}
} else if (calendar[row][col] >= this.startDate && calendar[row][col] <= this.endDate) {
cname += ' in-range ';
if (calendar[row][col].isSame(this.startDate)) { cname += ' start-date '; }
if (calendar[row][col].isSame(this.endDate)) { cname += ' end-date '; }
}
var title = 'r' + row + 'c' + col;
html += '<td class="' + cname.replace(/\s+/g, ' ').replace(/^\s?(.*?)\s?$/, '$1') + '" data-title="' + title + '">' + calendar[row][col].date() + '</td>';
}
html += '</tr>';
}
html += '</tbody>';
html += '</table>';
html += '</div>';
if (this.timePicker) {
html += '<div class="calendar-time">';
html += '<select class="hourselect">';
var start = 0;
var end = 23;
var selected_hour = selected.hour();
if (this.timePicker12Hour) {
start = 1;
end = 12;
if (selected_hour >= 12)
selected_hour -= 12;
if (selected_hour == 0)
selected_hour = 12;
}
for (var i = start; i <= end; i++) {
if (i == selected_hour) {
html += '<option value="' + i + '" selected="selected">' + i + '</option>';
} else {
html += '<option value="' + i + '">' + i + '</option>';
}
}
html += '</select> : ';
html += '<select class="minuteselect">';
for (var i = 0; i < 60; i += this.timePickerIncrement) {
var num = i;
if (num < 10)
num = '0' + num;
if (i == selected.minute()) {
html += '<option value="' + i + '" selected="selected">' + num + '</option>';
} else {
html += '<option value="' + i + '">' + num + '</option>';
}
}
html += '</select> ';
if (this.timePicker12Hour) {
html += '<select class="ampmselect">';
if (selected.hour() >= 12) {
html += '<option value="AM">AM</option><option value="PM" selected="selected">PM</option>';
} else {
html += '<option value="AM" selected="selected">AM</option><option value="PM">PM</option>';
}
html += '</select>';
}
html += '</div>';
}
return html;
}
};
$.fn.daterangepicker = function (options, cb) {
this.each(function () {
var el = $(this);
if (!el.data('daterangepicker'))
el.data('daterangepicker', new DateRangePicker(el, options, cb));
});
return this;
};
}(window.jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment