daterangepicker.js 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. /**
  2. * @version: 1.3.8
  3. * @author: Dan Grossman http://www.dangrossman.info/
  4. * @date: 2014-07-10
  5. * @copyright: Copyright (c) 2012-2014 Dan Grossman. All rights reserved.
  6. * @license: Licensed under Apache License v2.0. See http://www.apache.org/licenses/LICENSE-2.0
  7. * @website: http://www.improvely.com/
  8. */
  9. !function ($, moment) {
  10. var DateRangePicker = function (element, options, cb) {
  11. // by default, the daterangepicker element is placed at the bottom of HTML body
  12. this.parentEl = 'body';
  13. //element that triggered the date range picker
  14. this.element = $(element);
  15. //tracks visible state
  16. this.isShowing = false;
  17. //create the picker HTML object
  18. var DRPTemplate = '<div class="daterangepicker dropdown-menu">' +
  19. '<div class="calendar left"></div>' +
  20. '<div class="calendar right"></div>' +
  21. '<div class="ranges">' +
  22. '<div class="range_inputs">' +
  23. '<div class="daterangepicker_start_input">' +
  24. '<label for="daterangepicker_start"></label>' +
  25. '<input class="input-mini" type="text" name="daterangepicker_start" value="" readonly="readonly" />' +
  26. '</div>' +
  27. '<div class="daterangepicker_end_input">' +
  28. '<label for="daterangepicker_end"></label>' +
  29. '<input class="input-mini" type="text" name="daterangepicker_end" value="" readonly="readonly" />' +
  30. '</div>' +
  31. '<button class="applyBtn" disabled="disabled"></button>&nbsp;' +
  32. '<button class="cancelBtn"></button>' +
  33. '</div>' +
  34. '</div>' +
  35. '</div>';
  36. //custom options
  37. if (typeof options !== 'object' || options === null)
  38. options = {};
  39. this.parentEl = (typeof options === 'object' && options.parentEl && $(options.parentEl).length) ? $(options.parentEl) : $(this.parentEl);
  40. this.container = $(DRPTemplate).appendTo(this.parentEl);
  41. this.setOptions(options, cb);
  42. //apply CSS classes and labels to buttons
  43. var c = this.container;
  44. $.each(this.buttonClasses, function (idx, val) {
  45. c.find('button').addClass(val);
  46. });
  47. this.container.find('.daterangepicker_start_input label').html(this.locale.fromLabel);
  48. this.container.find('.daterangepicker_end_input label').html(this.locale.toLabel);
  49. if (this.applyClass.length)
  50. this.container.find('.applyBtn').addClass(this.applyClass);
  51. if (this.cancelClass.length)
  52. this.container.find('.cancelBtn').addClass(this.cancelClass);
  53. this.container.find('.applyBtn').html(this.locale.applyLabel);
  54. this.container.find('.cancelBtn').html(this.locale.cancelLabel);
  55. //event listeners
  56. this.container.find('.calendar')
  57. .on('click.daterangepicker', '.prev', $.proxy(this.clickPrev, this))
  58. .on('click.daterangepicker', '.next', $.proxy(this.clickNext, this))
  59. .on('click.daterangepicker', 'td.available', $.proxy(this.clickDate, this))
  60. .on('mouseenter.daterangepicker', 'td.available', $.proxy(this.enterDate, this))
  61. .on('mouseleave.daterangepicker', 'td.available', $.proxy(this.updateFormInputs, this))
  62. .on('change.daterangepicker', 'select.yearselect', $.proxy(this.updateMonthYear, this))
  63. .on('change.daterangepicker', 'select.monthselect', $.proxy(this.updateMonthYear, this))
  64. .on('change.daterangepicker', 'select.hourselect,select.minuteselect,select.ampmselect', $.proxy(this.updateTime, this));
  65. this.container.find('.ranges')
  66. .on('click.daterangepicker', 'button.applyBtn', $.proxy(this.clickApply, this))
  67. .on('click.daterangepicker', 'button.cancelBtn', $.proxy(this.clickCancel, this))
  68. .on('click.daterangepicker', '.daterangepicker_start_input,.daterangepicker_end_input', $.proxy(this.showCalendars, this))
  69. .on('click.daterangepicker', 'li', $.proxy(this.clickRange, this))
  70. .on('mouseenter.daterangepicker', 'li', $.proxy(this.enterRange, this))
  71. .on('mouseleave.daterangepicker', 'li', $.proxy(this.updateFormInputs, this));
  72. if (this.element.is('input')) {
  73. this.element.on({
  74. 'click.daterangepicker': $.proxy(this.show, this),
  75. 'focus.daterangepicker': $.proxy(this.show, this),
  76. 'keyup.daterangepicker': $.proxy(this.updateFromControl, this)
  77. });
  78. } else {
  79. this.element.on('click.daterangepicker', $.proxy(this.toggle, this));
  80. }
  81. };
  82. DateRangePicker.prototype = {
  83. constructor: DateRangePicker,
  84. setOptions: function(options, callback) {
  85. this.startDate = moment().startOf('minute');
  86. this.endDate = moment().endOf('day');
  87. this.minDate = false;
  88. this.maxDate = false;
  89. this.dateLimit = false;
  90. this.showDropdowns = false;
  91. this.showWeekNumbers = false;
  92. this.timePicker = false;
  93. this.timePickerIncrement = 30;
  94. this.timePicker12Hour = true;
  95. this.singleDatePicker = false;
  96. this.ranges = {};
  97. this.opens = 'right';
  98. if (this.element.hasClass('pull-right'))
  99. this.opens = 'left';
  100. this.buttonClasses = ['btn', 'btn-small btn-sm'];
  101. this.applyClass = 'btn-success';
  102. this.cancelClass = 'btn-default';
  103. this.format = 'MM/DD/YYYY';
  104. this.separator = ' - ';
  105. this.locale = {
  106. applyLabel: 'Apply',
  107. cancelLabel: 'Cancel',
  108. fromLabel: 'From',
  109. toLabel: 'To',
  110. weekLabel: 'W',
  111. customRangeLabel: 'Custom Range',
  112. daysOfWeek: moment()._lang._weekdaysMin.slice(),
  113. monthNames: moment()._lang._monthsShort.slice(),
  114. firstDay: 0
  115. };
  116. this.cb = function () { };
  117. if (typeof options.format === 'string')
  118. this.format = options.format;
  119. if (typeof options.separator === 'string')
  120. this.separator = options.separator;
  121. if (typeof options.startDate === 'string')
  122. this.startDate = moment(options.startDate, this.format);
  123. if (typeof options.endDate === 'string')
  124. this.endDate = moment(options.endDate, this.format);
  125. if (typeof options.minDate === 'string')
  126. this.minDate = moment(options.minDate, this.format);
  127. if (typeof options.maxDate === 'string')
  128. this.maxDate = moment(options.maxDate, this.format);
  129. if (typeof options.startDate === 'object')
  130. this.startDate = moment(options.startDate);
  131. if (typeof options.endDate === 'object')
  132. this.endDate = moment(options.endDate);
  133. if (typeof options.minDate === 'object')
  134. this.minDate = moment(options.minDate);
  135. if (typeof options.maxDate === 'object')
  136. this.maxDate = moment(options.maxDate);
  137. if (typeof options.applyClass === 'string')
  138. this.applyClass = options.applyClass;
  139. if (typeof options.cancelClass === 'string')
  140. this.cancelClass = options.cancelClass;
  141. if (typeof options.dateLimit === 'object')
  142. this.dateLimit = options.dateLimit;
  143. // update day names order to firstDay
  144. if (typeof options.locale === 'object') {
  145. if (typeof options.locale.daysOfWeek === 'object') {
  146. // Create a copy of daysOfWeek to avoid modification of original
  147. // options object for reusability in multiple daterangepicker instances
  148. this.locale.daysOfWeek = options.locale.daysOfWeek.slice();
  149. }
  150. if (typeof options.locale.monthNames === 'object') {
  151. this.locale.monthNames = options.locale.monthNames.slice();
  152. }
  153. if (typeof options.locale.firstDay === 'number') {
  154. this.locale.firstDay = options.locale.firstDay;
  155. var iterator = options.locale.firstDay;
  156. while (iterator > 0) {
  157. this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift());
  158. iterator--;
  159. }
  160. }
  161. if (typeof options.locale.applyLabel === 'string') {
  162. this.locale.applyLabel = options.locale.applyLabel;
  163. }
  164. if (typeof options.locale.cancelLabel === 'string') {
  165. this.locale.cancelLabel = options.locale.cancelLabel;
  166. }
  167. if (typeof options.locale.fromLabel === 'string') {
  168. this.locale.fromLabel = options.locale.fromLabel;
  169. }
  170. if (typeof options.locale.toLabel === 'string') {
  171. this.locale.toLabel = options.locale.toLabel;
  172. }
  173. if (typeof options.locale.weekLabel === 'string') {
  174. this.locale.weekLabel = options.locale.weekLabel;
  175. }
  176. if (typeof options.locale.customRangeLabel === 'string') {
  177. this.locale.customRangeLabel = options.locale.customRangeLabel;
  178. }
  179. }
  180. if (typeof options.opens === 'string')
  181. this.opens = options.opens;
  182. if (typeof options.showWeekNumbers === 'boolean') {
  183. this.showWeekNumbers = options.showWeekNumbers;
  184. }
  185. if (typeof options.buttonClasses === 'string') {
  186. this.buttonClasses = [options.buttonClasses];
  187. }
  188. if (typeof options.buttonClasses === 'object') {
  189. this.buttonClasses = options.buttonClasses;
  190. }
  191. if (typeof options.showDropdowns === 'boolean') {
  192. this.showDropdowns = options.showDropdowns;
  193. }
  194. if (typeof options.singleDatePicker === 'boolean') {
  195. this.singleDatePicker = options.singleDatePicker;
  196. }
  197. if (typeof options.timePicker === 'boolean') {
  198. this.timePicker = options.timePicker;
  199. }
  200. if (typeof options.timePickerIncrement === 'number') {
  201. this.timePickerIncrement = options.timePickerIncrement;
  202. }
  203. if (typeof options.timePicker12Hour === 'boolean') {
  204. this.timePicker12Hour = options.timePicker12Hour;
  205. }
  206. var start, end, range;
  207. //if no start/end dates set, check if an input element contains initial values
  208. if (typeof options.startDate === 'undefined' && typeof options.endDate === 'undefined') {
  209. if ($(this.element).is('input[type=text]')) {
  210. var val = $(this.element).val();
  211. var split = val.split(this.separator);
  212. start = end = null;
  213. if (split.length == 2) {
  214. start = moment(split[0], this.format);
  215. end = moment(split[1], this.format);
  216. } else if (this.singleDatePicker) {
  217. start = moment(val, this.format);
  218. end = moment(val, this.format);
  219. }
  220. if (start !== null && end !== null) {
  221. this.startDate = start;
  222. this.endDate = end;
  223. }
  224. }
  225. }
  226. if (typeof options.ranges === 'object') {
  227. for (range in options.ranges) {
  228. start = moment(options.ranges[range][0]);
  229. end = moment(options.ranges[range][1]);
  230. // If we have a min/max date set, bound this range
  231. // to it, but only if it would otherwise fall
  232. // outside of the min/max.
  233. if (this.minDate && start.isBefore(this.minDate))
  234. start = moment(this.minDate);
  235. if (this.maxDate && end.isAfter(this.maxDate))
  236. end = moment(this.maxDate);
  237. // If the end of the range is before the minimum (if min is set) OR
  238. // the start of the range is after the max (also if set) don't display this
  239. // range option.
  240. if ((this.minDate && end.isBefore(this.minDate)) || (this.maxDate && start.isAfter(this.maxDate))) {
  241. continue;
  242. }
  243. this.ranges[range] = [start, end];
  244. }
  245. var list = '<ul>';
  246. for (range in this.ranges) {
  247. list += '<li>' + range + '</li>';
  248. }
  249. list += '<li>' + this.locale.customRangeLabel + '</li>';
  250. list += '</ul>';
  251. this.container.find('.ranges ul').remove();
  252. this.container.find('.ranges').prepend(list);
  253. }
  254. if (typeof callback === 'function') {
  255. this.cb = callback;
  256. }
  257. if (!this.timePicker) {
  258. this.startDate = this.startDate.startOf('day');
  259. this.endDate = this.endDate.endOf('day');
  260. }
  261. if (this.singleDatePicker) {
  262. this.opens = 'right';
  263. this.container.find('.calendar.right').show();
  264. this.container.find('.calendar.left').hide();
  265. this.container.find('.ranges').hide();
  266. if (!this.container.find('.calendar.right').hasClass('single'))
  267. this.container.find('.calendar.right').addClass('single');
  268. } else {
  269. this.container.find('.calendar.right').removeClass('single');
  270. this.container.find('.ranges').show();
  271. }
  272. this.oldStartDate = this.startDate.clone();
  273. this.oldEndDate = this.endDate.clone();
  274. this.oldChosenLabel = this.chosenLabel;
  275. this.leftCalendar = {
  276. month: moment([this.startDate.year(), this.startDate.month(), 1, this.startDate.hour(), this.startDate.minute()]),
  277. calendar: []
  278. };
  279. this.rightCalendar = {
  280. month: moment([this.endDate.year(), this.endDate.month(), 1, this.endDate.hour(), this.endDate.minute()]),
  281. calendar: []
  282. };
  283. if (this.opens == 'right') {
  284. //swap calendar positions
  285. var left = this.container.find('.calendar.left');
  286. var right = this.container.find('.calendar.right');
  287. left.removeClass('left').addClass('right');
  288. right.removeClass('right').addClass('left');
  289. }
  290. if (typeof options.ranges === 'undefined' && !this.singleDatePicker) {
  291. this.container.addClass('show-calendar');
  292. }
  293. this.container.addClass('opens' + this.opens);
  294. this.updateView();
  295. this.updateCalendars();
  296. },
  297. setStartDate: function(startDate) {
  298. if (typeof startDate === 'string')
  299. this.startDate = moment(startDate, this.format);
  300. if (typeof startDate === 'object')
  301. this.startDate = moment(startDate);
  302. if (!this.timePicker)
  303. this.startDate = this.startDate.startOf('day');
  304. this.oldStartDate = this.startDate.clone();
  305. this.updateView();
  306. this.updateCalendars();
  307. this.updateInputText();
  308. },
  309. setEndDate: function(endDate) {
  310. if (typeof endDate === 'string')
  311. this.endDate = moment(endDate, this.format);
  312. if (typeof endDate === 'object')
  313. this.endDate = moment(endDate);
  314. if (!this.timePicker)
  315. this.endDate = this.endDate.endOf('day');
  316. this.oldEndDate = this.endDate.clone();
  317. this.updateView();
  318. this.updateCalendars();
  319. this.updateInputText();
  320. },
  321. updateView: function () {
  322. this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year()).hour(this.startDate.hour()).minute(this.startDate.minute());
  323. this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year()).hour(this.endDate.hour()).minute(this.endDate.minute());
  324. this.updateFormInputs();
  325. },
  326. updateFormInputs: function () {
  327. this.container.find('input[name=daterangepicker_start]').val(this.startDate.format(this.format));
  328. this.container.find('input[name=daterangepicker_end]').val(this.endDate.format(this.format));
  329. if (this.startDate.isSame(this.endDate) || this.startDate.isBefore(this.endDate)) {
  330. this.container.find('button.applyBtn').removeAttr('disabled');
  331. } else {
  332. this.container.find('button.applyBtn').attr('disabled', 'disabled');
  333. }
  334. },
  335. updateFromControl: function () {
  336. if (!this.element.is('input')) return;
  337. if (!this.element.val().length) return;
  338. var dateString = this.element.val().split(this.separator),
  339. start = null,
  340. end = null;
  341. if(dateString.length === 2) {
  342. start = moment(dateString[0], this.format);
  343. end = moment(dateString[1], this.format);
  344. }
  345. if (this.singleDatePicker || start === null || end === null) {
  346. start = moment(this.element.val(), this.format);
  347. end = start;
  348. }
  349. if (end.isBefore(start)) return;
  350. this.oldStartDate = this.startDate.clone();
  351. this.oldEndDate = this.endDate.clone();
  352. this.startDate = start;
  353. this.endDate = end;
  354. if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
  355. this.notify();
  356. this.updateCalendars();
  357. },
  358. notify: function () {
  359. this.updateView();
  360. this.cb(this.startDate, this.endDate, this.chosenLabel);
  361. },
  362. move: function () {
  363. var parentOffset = { top: 0, left: 0 };
  364. if (!this.parentEl.is('body')) {
  365. parentOffset = {
  366. top: this.parentEl.offset().top - this.parentEl.scrollTop(),
  367. left: this.parentEl.offset().left - this.parentEl.scrollLeft()
  368. };
  369. }
  370. if (this.opens == 'left') {
  371. this.container.css({
  372. top: this.element.offset().top + this.element.outerHeight() - parentOffset.top,
  373. right: $(window).width() - this.element.offset().left - this.element.outerWidth() - parentOffset.left,
  374. left: 'auto'
  375. });
  376. if (this.container.offset().left < 0) {
  377. this.container.css({
  378. right: 'auto',
  379. left: 9
  380. });
  381. }
  382. } else {
  383. this.container.css({
  384. top: this.element.offset().top + this.element.outerHeight() - parentOffset.top,
  385. left: this.element.offset().left - parentOffset.left,
  386. right: 'auto'
  387. });
  388. if (this.container.offset().left + this.container.outerWidth() > $(window).width()) {
  389. this.container.css({
  390. left: 'auto',
  391. right: 0
  392. });
  393. }
  394. }
  395. },
  396. toggle: function (e) {
  397. if (this.element.hasClass('active')) {
  398. this.hide();
  399. } else {
  400. this.show();
  401. }
  402. },
  403. show: function (e) {
  404. if (this.isShowing) return;
  405. this.element.addClass('active');
  406. this.container.show();
  407. this.move();
  408. // Create a click proxy that is private to this instance of datepicker, for unbinding
  409. this._outsideClickProxy = $.proxy(function (e) { this.outsideClick(e); }, this);
  410. // Bind global datepicker mousedown for hiding and
  411. $(document)
  412. .on('mousedown.daterangepicker', this._outsideClickProxy)
  413. // also explicitly play nice with Bootstrap dropdowns, which stopPropagation when clicking them
  414. .on('click.daterangepicker', '[data-toggle=dropdown]', this._outsideClickProxy)
  415. // and also close when focus changes to outside the picker (eg. tabbing between controls)
  416. .on('focusin.daterangepicker', this._outsideClickProxy);
  417. this.isShowing = true;
  418. this.element.trigger('show.daterangepicker', this);
  419. },
  420. outsideClick: function (e) {
  421. var target = $(e.target);
  422. // if the page is clicked anywhere except within the daterangerpicker/button
  423. // itself then call this.hide()
  424. if (
  425. target.closest(this.element).length ||
  426. target.closest(this.container).length ||
  427. target.closest('.calendar-date').length
  428. ) return;
  429. this.hide();
  430. },
  431. hide: function (e) {
  432. if (!this.isShowing) return;
  433. $(document)
  434. .off('mousedown.daterangepicker')
  435. .off('click.daterangepicker', '[data-toggle=dropdown]')
  436. .off('focusin.daterangepicker');
  437. this.element.removeClass('active');
  438. this.container.hide();
  439. if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
  440. this.notify();
  441. this.oldStartDate = this.startDate.clone();
  442. this.oldEndDate = this.endDate.clone();
  443. this.isShowing = false;
  444. this.element.trigger('hide.daterangepicker', this);
  445. },
  446. enterRange: function (e) {
  447. // mouse pointer has entered a range label
  448. var label = e.target.innerHTML;
  449. if (label == this.locale.customRangeLabel) {
  450. date = new Date();
  451. year = date.getFullYear();
  452. month = date.getMonth() + 1;
  453. if (month < 10) {
  454. month = '0' + month;
  455. }
  456. day = date.getDate();
  457. week_date = this.addDate(month+'/'+day+'/'+year, -7);
  458. week_year = week_date.getFullYear();
  459. week_month = week_date.getMonth() + 1;
  460. if (week_month < 10) {
  461. week_month = '0' + week_month;
  462. }
  463. week_day = week_date.getDate();
  464. this.container.find('input[name=daterangepicker_start]').val(week_year + '-' + week_month + '-' + week_day);
  465. this.container.find('input[name=daterangepicker_end]').val(year + '-' + month + '-' + day);
  466. } else {
  467. var dates = this.ranges[label];
  468. this.container.find('input[name=daterangepicker_start]').val(dates[0].format(this.format));
  469. this.container.find('input[name=daterangepicker_end]').val(dates[1].format(this.format));
  470. }
  471. },
  472. showCalendars: function() {
  473. this.container.addClass('show-calendar');
  474. this.move();
  475. this.element.trigger('showCalendar.daterangepicker', this);
  476. },
  477. hideCalendars: function() {
  478. this.container.removeClass('show-calendar');
  479. this.element.trigger('hideCalendar.daterangepicker', this);
  480. },
  481. updateInputText: function() {
  482. if (this.element.is('input') && !this.singleDatePicker) {
  483. this.element.val(this.startDate.format(this.format) + this.separator + this.endDate.format(this.format));
  484. } else if (this.element.is('input')) {
  485. this.element.val(this.startDate.format(this.format));
  486. } else {
  487. }
  488. },
  489. addDate: function(date, count) {
  490. var a = new Date(date);
  491. a = a.valueOf();
  492. a = a + count * 24 * 60 * 60 * 1000;
  493. a = new Date(a);
  494. return a;
  495. },
  496. clickRange: function (e) {
  497. var label = e.target.innerHTML;
  498. this.chosenLabel = label;
  499. if (label == this.locale.customRangeLabel) {
  500. this.showCalendars();
  501. date = new Date();
  502. year = date.getFullYear();
  503. month = date.getMonth() + 1;
  504. if (month < 10) {
  505. month = '0' + month;
  506. }
  507. day = date.getDate();
  508. week_date = this.addDate(month+'/'+day+'/'+year, -7);
  509. week_year = week_date.getFullYear();
  510. week_month = week_date.getMonth() + 1;
  511. if (week_month < 10) {
  512. week_month = '0' + week_month;
  513. }
  514. week_day = week_date.getDate();
  515. this.leftCalendar.month.month(week_month).year(week_year).hour(this.startDate.hour()).minute(this.startDate.minute());
  516. this.rightCalendar.month.month(month).year(year).hour(this.endDate.hour()).minute(this.endDate.minute());
  517. this.updateCalendars();
  518. } else {
  519. var dates = this.ranges[label];
  520. this.startDate = dates[0];
  521. this.endDate = dates[1];
  522. if (!this.timePicker) {
  523. this.startDate.startOf('day');
  524. this.endDate.endOf('day');
  525. }
  526. this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year()).hour(this.startDate.hour()).minute(this.startDate.minute());
  527. this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year()).hour(this.endDate.hour()).minute(this.endDate.minute());
  528. this.updateCalendars();
  529. this.updateInputText();
  530. this.hideCalendars();
  531. this.hide();
  532. this.element.trigger('apply.daterangepicker', this);
  533. }
  534. },
  535. clickPrev: function (e) {
  536. var cal = $(e.target).parents('.calendar');
  537. if (cal.hasClass('left')) {
  538. this.leftCalendar.month.subtract('month', 1);
  539. } else {
  540. this.rightCalendar.month.subtract('month', 1);
  541. }
  542. this.updateCalendars();
  543. },
  544. clickNext: function (e) {
  545. var cal = $(e.target).parents('.calendar');
  546. if (cal.hasClass('left')) {
  547. this.leftCalendar.month.add('month', 1);
  548. } else {
  549. this.rightCalendar.month.add('month', 1);
  550. }
  551. this.updateCalendars();
  552. },
  553. enterDate: function (e) {
  554. var title = $(e.target).attr('data-title');
  555. var row = title.substr(1, 1);
  556. var col = title.substr(3, 1);
  557. var cal = $(e.target).parents('.calendar');
  558. if (cal.hasClass('left')) {
  559. this.container.find('input[name=daterangepicker_start]').val(this.leftCalendar.calendar[row][col].format(this.format));
  560. } else {
  561. this.container.find('input[name=daterangepicker_end]').val(this.rightCalendar.calendar[row][col].format(this.format));
  562. }
  563. },
  564. clickDate: function (e) {
  565. var title = $(e.target).attr('data-title');
  566. var row = title.substr(1, 1);
  567. var col = title.substr(3, 1);
  568. var cal = $(e.target).parents('.calendar');
  569. var startDate, endDate;
  570. if (cal.hasClass('left')) {
  571. startDate = this.leftCalendar.calendar[row][col];
  572. endDate = this.endDate;
  573. if (typeof this.dateLimit === 'object') {
  574. var maxDate = moment(startDate).add(this.dateLimit).startOf('day');
  575. if (endDate.isAfter(maxDate)) {
  576. endDate = maxDate;
  577. }
  578. }
  579. } else {
  580. startDate = this.startDate;
  581. endDate = this.rightCalendar.calendar[row][col];
  582. if (typeof this.dateLimit === 'object') {
  583. var minDate = moment(endDate).subtract(this.dateLimit).startOf('day');
  584. if (startDate.isBefore(minDate)) {
  585. startDate = minDate;
  586. }
  587. }
  588. }
  589. if (this.singleDatePicker && cal.hasClass('left')) {
  590. endDate = startDate.clone();
  591. } else if (this.singleDatePicker && cal.hasClass('right')) {
  592. startDate = endDate.clone();
  593. }
  594. cal.find('td').removeClass('active');
  595. if (startDate.isSame(endDate) || startDate.isBefore(endDate)) {
  596. $(e.target).addClass('active');
  597. this.startDate = startDate;
  598. this.endDate = endDate;
  599. this.chosenLabel = this.locale.customRangeLabel;
  600. } else if (startDate.isAfter(endDate)) {
  601. $(e.target).addClass('active');
  602. var difference = this.endDate.diff(this.startDate);
  603. this.startDate = startDate;
  604. this.endDate = moment(startDate).add('ms', difference);
  605. this.chosenLabel = this.locale.customRangeLabel;
  606. }
  607. this.leftCalendar.month.month(this.startDate.month()).year(this.startDate.year());
  608. this.rightCalendar.month.month(this.endDate.month()).year(this.endDate.year());
  609. this.updateCalendars();
  610. if (!this.timePicker)
  611. endDate.endOf('day');
  612. if (this.singleDatePicker)
  613. this.clickApply();
  614. },
  615. clickApply: function (e) {
  616. this.updateInputText();
  617. this.hide();
  618. this.element.trigger('apply.daterangepicker', this);
  619. },
  620. clickCancel: function (e) {
  621. this.startDate = this.oldStartDate;
  622. this.endDate = this.oldEndDate;
  623. this.chosenLabel = this.oldChosenLabel;
  624. this.updateView();
  625. this.updateCalendars();
  626. this.hide();
  627. this.element.trigger('cancel.daterangepicker', this);
  628. },
  629. updateMonthYear: function (e) {
  630. var isLeft = $(e.target).closest('.calendar').hasClass('left'),
  631. leftOrRight = isLeft ? 'left' : 'right',
  632. cal = this.container.find('.calendar.'+leftOrRight);
  633. // Month must be Number for new moment versions
  634. var month = parseInt(cal.find('.monthselect').val(), 10);
  635. var year = cal.find('.yearselect').val();
  636. this[leftOrRight+'Calendar'].month.month(month).year(year);
  637. this.updateCalendars();
  638. },
  639. updateTime: function(e) {
  640. var cal = $(e.target).closest('.calendar'),
  641. isLeft = cal.hasClass('left');
  642. var hour = parseInt(cal.find('.hourselect').val(), 10);
  643. var minute = parseInt(cal.find('.minuteselect').val(), 10);
  644. if (this.timePicker12Hour) {
  645. var ampm = cal.find('.ampmselect').val();
  646. if (ampm === 'PM' && hour < 12)
  647. hour += 12;
  648. if (ampm === 'AM' && hour === 12)
  649. hour = 0;
  650. }
  651. if (isLeft) {
  652. var start = this.startDate.clone();
  653. start.hour(hour);
  654. start.minute(minute);
  655. this.startDate = start;
  656. this.leftCalendar.month.hour(hour).minute(minute);
  657. } else {
  658. var end = this.endDate.clone();
  659. end.hour(hour);
  660. end.minute(minute);
  661. this.endDate = end;
  662. this.rightCalendar.month.hour(hour).minute(minute);
  663. }
  664. this.updateCalendars();
  665. },
  666. updateCalendars: function () {
  667. this.leftCalendar.calendar = this.buildCalendar(this.leftCalendar.month.month(), this.leftCalendar.month.year(), this.leftCalendar.month.hour(), this.leftCalendar.month.minute(), 'left');
  668. this.rightCalendar.calendar = this.buildCalendar(this.rightCalendar.month.month(), this.rightCalendar.month.year(), this.rightCalendar.month.hour(), this.rightCalendar.month.minute(), 'right');
  669. this.container.find('.calendar.left').empty().html(this.renderCalendar(this.leftCalendar.calendar, this.startDate, this.minDate, this.maxDate));
  670. this.container.find('.calendar.right').empty().html(this.renderCalendar(this.rightCalendar.calendar, this.endDate, this.startDate, this.maxDate));
  671. this.container.find('.ranges li').removeClass('active');
  672. var customRange = true;
  673. var i = 0;
  674. for (var range in this.ranges) {
  675. if (this.timePicker) {
  676. if (this.startDate.isSame(this.ranges[range][0]) && this.endDate.isSame(this.ranges[range][1])) {
  677. customRange = false;
  678. this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')')
  679. .addClass('active').html();
  680. }
  681. } else {
  682. //ignore times when comparing dates if time picker is not enabled
  683. 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')) {
  684. customRange = false;
  685. this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')')
  686. .addClass('active').html();
  687. }
  688. }
  689. i++;
  690. }
  691. if (customRange) {
  692. this.chosenLabel = this.container.find('.ranges li:last')
  693. .addClass('active').html();
  694. }
  695. },
  696. buildCalendar: function (month, year, hour, minute, side) {
  697. var firstDay = moment([year, month, 1]);
  698. var lastMonth = moment(firstDay).subtract('month', 1).month();
  699. var lastYear = moment(firstDay).subtract('month', 1).year();
  700. var daysInLastMonth = moment([lastYear, lastMonth]).daysInMonth();
  701. var dayOfWeek = firstDay.day();
  702. var i;
  703. //initialize a 6 rows x 7 columns array for the calendar
  704. var calendar = [];
  705. for (i = 0; i < 6; i++) {
  706. calendar[i] = [];
  707. }
  708. //populate the calendar with date objects
  709. var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1;
  710. if (startDay > daysInLastMonth)
  711. startDay -= 7;
  712. if (dayOfWeek == this.locale.firstDay)
  713. startDay = daysInLastMonth - 6;
  714. var curDate = moment([lastYear, lastMonth, startDay, 12, minute]);
  715. var col, row;
  716. for (i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = moment(curDate).add('hour', 24)) {
  717. if (i > 0 && col % 7 === 0) {
  718. col = 0;
  719. row++;
  720. }
  721. calendar[row][col] = curDate.clone().hour(hour);
  722. curDate.hour(12);
  723. }
  724. return calendar;
  725. },
  726. renderDropdowns: function (selected, minDate, maxDate) {
  727. var currentMonth = selected.month();
  728. var monthHtml = '<select class="monthselect">';
  729. var inMinYear = false;
  730. var inMaxYear = false;
  731. for (var m = 0; m < 12; m++) {
  732. if ((!inMinYear || m >= minDate.month()) && (!inMaxYear || m <= maxDate.month())) {
  733. monthHtml += "<option value='" + m + "'" +
  734. (m === currentMonth ? " selected='selected'" : "") +
  735. ">" + this.locale.monthNames[m] + "</option>";
  736. }
  737. }
  738. monthHtml += "</select>";
  739. var currentYear = selected.year();
  740. var maxYear = (maxDate && maxDate.year()) || (currentYear + 5);
  741. var minYear = (minDate && minDate.year()) || (currentYear - 50);
  742. var yearHtml = '<select class="yearselect">';
  743. for (var y = minYear; y <= maxYear; y++) {
  744. yearHtml += '<option value="' + y + '"' +
  745. (y === currentYear ? ' selected="selected"' : '') +
  746. '>' + y + '</option>';
  747. }
  748. yearHtml += '</select>';
  749. return monthHtml + yearHtml;
  750. },
  751. renderCalendar: function (calendar, selected, minDate, maxDate) {
  752. var html = '<div class="calendar-date">';
  753. html += '<table class="table-condensed">';
  754. html += '<thead>';
  755. html += '<tr>';
  756. // add empty cell for week number
  757. if (this.showWeekNumbers)
  758. html += '<th></th>';
  759. if (!minDate || minDate.isBefore(calendar[1][1])) {
  760. html += '<th class="prev available"><i class="fa fa-arrow-left icon-arrow-left glyphicon glyphicon-arrow-left"></i></th>';
  761. } else {
  762. html += '<th></th>';
  763. }
  764. var dateHtml = this.locale.monthNames[calendar[1][1].month()] + calendar[1][1].format(" YYYY");
  765. if (this.showDropdowns) {
  766. dateHtml = this.renderDropdowns(calendar[1][1], minDate, maxDate);
  767. }
  768. html += '<th colspan="5" class="month">' + dateHtml + '</th>';
  769. if (!maxDate || maxDate.isAfter(calendar[1][1])) {
  770. html += '<th class="next available"><i class="fa fa-arrow-right icon-arrow-right glyphicon glyphicon-arrow-right"></i></th>';
  771. } else {
  772. html += '<th></th>';
  773. }
  774. html += '</tr>';
  775. html += '<tr>';
  776. // add week number label
  777. if (this.showWeekNumbers)
  778. html += '<th class="week">' + this.locale.weekLabel + '</th>';
  779. $.each(this.locale.daysOfWeek, function (index, dayOfWeek) {
  780. html += '<th>' + dayOfWeek + '</th>';
  781. });
  782. html += '</tr>';
  783. html += '</thead>';
  784. html += '<tbody>';
  785. for (var row = 0; row < 6; row++) {
  786. html += '<tr>';
  787. // add week number
  788. if (this.showWeekNumbers)
  789. html += '<td class="week">' + calendar[row][0].week() + '</td>';
  790. for (var col = 0; col < 7; col++) {
  791. var cname = 'available ';
  792. cname += (calendar[row][col].month() == calendar[1][1].month()) ? '' : 'off';
  793. if ((minDate && calendar[row][col].isBefore(minDate, 'day')) || (maxDate && calendar[row][col].isAfter(maxDate, 'day'))) {
  794. cname = ' off disabled ';
  795. } else if (calendar[row][col].format('YYYY-MM-DD') == selected.format('YYYY-MM-DD')) {
  796. cname += ' active ';
  797. if (calendar[row][col].format('YYYY-MM-DD') == this.startDate.format('YYYY-MM-DD')) {
  798. cname += ' start-date ';
  799. }
  800. if (calendar[row][col].format('YYYY-MM-DD') == this.endDate.format('YYYY-MM-DD')) {
  801. cname += ' end-date ';
  802. }
  803. } else if (calendar[row][col] >= this.startDate && calendar[row][col] <= this.endDate) {
  804. cname += ' in-range ';
  805. if (calendar[row][col].isSame(this.startDate)) { cname += ' start-date '; }
  806. if (calendar[row][col].isSame(this.endDate)) { cname += ' end-date '; }
  807. }
  808. var title = 'r' + row + 'c' + col;
  809. html += '<td class="' + cname.replace(/\s+/g, ' ').replace(/^\s?(.*?)\s?$/, '$1') + '" data-title="' + title + '">' + calendar[row][col].date() + '</td>';
  810. }
  811. html += '</tr>';
  812. }
  813. html += '</tbody>';
  814. html += '</table>';
  815. html += '</div>';
  816. var i;
  817. if (this.timePicker) {
  818. html += '<div class="calendar-time">';
  819. html += '<select class="hourselect">';
  820. var start = 0;
  821. var end = 23;
  822. var selected_hour = selected.hour();
  823. if (this.timePicker12Hour) {
  824. start = 1;
  825. end = 12;
  826. if (selected_hour >= 12)
  827. selected_hour -= 12;
  828. if (selected_hour === 0)
  829. selected_hour = 12;
  830. }
  831. for (i = start; i <= end; i++) {
  832. if (i == selected_hour) {
  833. html += '<option value="' + i + '" selected="selected">' + i + '</option>';
  834. } else {
  835. html += '<option value="' + i + '">' + i + '</option>';
  836. }
  837. }
  838. html += '</select> : ';
  839. html += '<select class="minuteselect">';
  840. for (i = 0; i < 60; i += this.timePickerIncrement) {
  841. var num = i;
  842. if (num < 10)
  843. num = '0' + num;
  844. if (i == selected.minute()) {
  845. html += '<option value="' + i + '" selected="selected">' + num + '</option>';
  846. } else {
  847. html += '<option value="' + i + '">' + num + '</option>';
  848. }
  849. }
  850. html += '</select> ';
  851. if (this.timePicker12Hour) {
  852. html += '<select class="ampmselect">';
  853. if (selected.hour() >= 12) {
  854. html += '<option value="AM">AM</option><option value="PM" selected="selected">PM</option>';
  855. } else {
  856. html += '<option value="AM" selected="selected">AM</option><option value="PM">PM</option>';
  857. }
  858. html += '</select>';
  859. }
  860. html += '</div>';
  861. }
  862. return html;
  863. },
  864. remove: function() {
  865. this.container.remove();
  866. this.element.off('.daterangepicker');
  867. this.element.removeData('daterangepicker');
  868. }
  869. };
  870. $.fn.daterangepicker = function (options, cb) {
  871. this.each(function () {
  872. var el = $(this);
  873. if (el.data('daterangepicker'))
  874. el.data('daterangepicker').remove();
  875. console.log(options)
  876. if(typeof(options) == 'object') {
  877. if(typeof(options.ranges) != 'object') {
  878. options.ranges = {};
  879. var now = new Date();
  880. var year = now.getFullYear();
  881. var month = now.getMonth();
  882. var day = now.getDate();
  883. options.ranges['今天'] = [new Date(year, month, day, 0, 0, 0), moment()];
  884. options.ranges['一周内'] = [moment().subtract('days', 6), moment()];
  885. options.ranges['二周内'] = [moment().subtract('days', 13), moment()];
  886. options.ranges['一月内'] = [moment().subtract('days', 29), moment()];
  887. }
  888. if(typeof(options.locale) != 'object') {
  889. options.locale = {
  890. applyLabel: "确定",
  891. cancelLabel: "取消",
  892. fromLabel: "从",
  893. toLabel: "至",
  894. weekLabel: "周",
  895. customRangeLabel: "日期范围",
  896. daysOfWeek: moment()._lang._weekdaysMin.slice(),
  897. monthNames: moment()._lang._monthsShort.slice(),
  898. firstDay: 0
  899. };
  900. }
  901. }
  902. el.data('daterangepicker', new DateRangePicker(el, options, cb));
  903. });
  904. return this;
  905. };
  906. }(window.jQuery, window.moment);