# All files / extensions dateUtils.js

21.05% Statements 8/38
0% Branches 0/22
0% Functions 0/7
28.57% Lines 8/28

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    436x

    6x

    6x

    6x

    6x

    6x

    6x

    6x
     export const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];

    export const getMaxDaysInMonth = (month, year) => {
      const m = MONTHS.indexOf(month.toLowerCase());
      const y = (typeof year === 'number') ? year : parseInt(year, 10);
      const date = new Date(y, m + 1, 0);
      if (isNaN(date)) return 0;
      return date.getDate();
    };

    export const isValidMonth = month => (typeof month === 'string' && MONTHS.indexOf(month.toLowerCase()) !== -1);

    // Intentionally using coalescence to determine if the input string / number is numeric
    // eslint-disable-next-line eqeqeq
    export const isValidYear = year => (Number(parseInt(year, 10)) == year);

    export const isValidDay = (month, day, year) => {
      const d = (typeof day !== 'number') ? parseInt(day, 10) : day;
      if (isNaN(d) || d < 1) return false;
      if (d <= 28) return true; // Don't check max days unless necessary
      const daysInMonth = getMaxDaysInMonth(month, year);
      return (d <= daysInMonth);
    };

    export const getDate = (month, day, year) => {
      const m = MONTHS.indexOf(month.toLowerCase());
      const d = parseInt(day, 10);
      const y = parseInt(year, 10);
      return new Date(y, m, d);
    };

    export const validateDate = (month, day, year) => {
      if (!isValidMonth(month)) throw new Error('Invalid month selected');
      if (!isValidYear(year)) throw new Error('Invalid year selected');
      if (!isValidDay(month, day, year)) throw new Error('Invalid day selected');
      const date = getDate(month, day, year);
      if (isNaN(date)) throw new Error('Invalid date');
      return date;
    };

    export const removeTimeFromDate = date => new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0, 0);