daterangepicker.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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. if(typeof(options) == 'object') {
  876. if(typeof(options.ranges) != 'object') {
  877. options.ranges = {};
  878. var now = new Date();
  879. var year = now.getFullYear();
  880. var month = now.getMonth();
  881. var day = now.getDate();
  882. options.ranges['今天'] = [new Date(year, month, day, 0, 0, 0), moment()];
  883. options.ranges['一周内'] = [moment().subtract('days', 6), moment()];
  884. options.ranges['二周内'] = [moment().subtract('days', 13), moment()];
  885. options.ranges['一月内'] = [moment().subtract('days', 29), moment()];
  886. }
  887. if(typeof(options.locale) != 'object') {
  888. options.locale = {
  889. applyLabel: "确定",
  890. cancelLabel: "取消",
  891. fromLabel: "从",
  892. toLabel: "至",
  893. weekLabel: "周",
  894. customRangeLabel: "日期范围",
  895. daysOfWeek: moment()._lang._weekdaysMin.slice(),
  896. monthNames: moment()._lang._monthsShort.slice(),
  897. firstDay: 0
  898. };
  899. }
  900. }
  901. el.data('daterangepicker', new DateRangePicker(el, options, cb));
  902. });
  903. return this;
  904. };
  905. }(window.jQuery, window.moment);