All files / elements/forms/DateField utils.js

100% Statements 11/11
87.5% Branches 14/16
100% Functions 3/3
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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      200x               10x 5x 4x         1x             10x 2x 1x       1x   1x    
import moment from 'moment';
import { dayPickerClassTypes, DEFAULT_DATE_FORMAT, DEFAULT_DATE_VALUE_FORMAT } from './constants';
 
export const dayPickerInputClassNames = dayPickerClassTypes.reduce((dayPickerClassNames, classType) => ({
  ...dayPickerClassNames,
  [classType]: `grape-ui-day-picker-${classType}`,
}), {});
 
/**
 *  Converts the Date from react-day-picker to a string value based on the valueFormat for saving to form controls, etc.
*/
export const formatForOnChange = (value, format, locale) => {
  if (value && value instanceof Date) {
    return moment(`${(value.getMonth() + 1)}/${value.getDate()}/${value.getFullYear()}}`, DEFAULT_DATE_FORMAT)
      .local()
      .locale(locale || 'en')
      .format(format || DEFAULT_DATE_VALUE_FORMAT);
  }
  return '';
};
 
/**
 *  Converts the Date from react-day-picker to a string value based on the formate for display on the input controls, etc.
 *  Not Used for now as we are using the default parseDate and formatDate
*/
export const formatForSelectedDay = (value, valueFormat, format, locale) => {
  if (value && typeof value === 'string') {
    const result = moment(value, valueFormat)
      .local()
      .locale(locale || 'en')
      .format(format);
    return result === 'Invalid date' ? undefined : result;
  }
  return undefined;
};