UNPKG

1.81 kBJavaScriptView Raw
1import moment from 'moment';
2import PropTypes from 'prop-types';
3
4const isoDateFormat = 'YYYY-MM-DD';
5
6export const isOutsideRange = (min, max, format = 'MM/DD/YYYY') => day => {
7 let isOutsideMax = false;
8 let isOutsideMin = false;
9
10 if (min) {
11 if (moment.isMoment(min)) {
12 isOutsideMin = day.isBefore(min);
13 }
14
15 if (typeof min === 'string') {
16 isOutsideMin = day.isBefore(
17 moment(min, [isoDateFormat, format, 'MMDDYYYY', 'YYYYMMDD'])
18 );
19 }
20
21 if (min.value !== undefined && min.units) {
22 isOutsideMin = day.isBefore(moment().subtract(min.value, min.units));
23 }
24 }
25
26 if (max) {
27 if (moment.isMoment(max)) {
28 isOutsideMax = day.isAfter(max);
29 }
30
31 if (typeof max === 'string') {
32 const maxMoment = moment(max, [
33 isoDateFormat,
34 format,
35 'MMDDYYYY',
36 'YYYYMMDD',
37 ]);
38 if (!maxMoment._f || maxMoment._f.indexOf('H') === -1) {
39 maxMoment.hour(23);
40 maxMoment.minute(59);
41 maxMoment.second(59);
42 }
43 isOutsideMax = day.isAfter(maxMoment);
44 }
45
46 if (max.value !== undefined && max.units) {
47 isOutsideMax = day.isAfter(moment().add(max.value, max.units));
48 }
49 }
50
51 return isOutsideMax || isOutsideMin;
52};
53
54export const limitPropType = PropTypes.oneOfType([
55 PropTypes.string,
56 PropTypes.shape({ value: PropTypes.number, units: PropTypes.string }),
57 PropTypes.shape({ _d: PropTypes.string, _isValid: PropTypes.func }), // moment prop type
58]);
59
60export const isSameDay = (a, b) => {
61 if (!moment.isMoment(a) || !moment(b)) return false;
62 // Compare least significant, most likely to change units first
63 // Moment's isSame clones moment inputs and is a tad slow
64 return (
65 a.date() === b.date() && a.month() === b.month() && a.year() === b.year()
66 );
67};