All files / helpers/date utils.js

53.84% Statements 7/13
46.15% Branches 6/13
100% Functions 1/1
54.54% Lines 6/11

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 37 38 39 40                    2x           2x 2x 2x           2x 2x                            
import moment from 'moment-timezone';
 
/**
 *
 * @param {*} dateValue -> date value to be validated
 * @param {*} todayDateOnNull -> if true, return today date if dateValue is null
 * @param {*} dateFormatFrom -> date format of dateValue | default: 'DD/MM/YYYY HH:mm:ss'
 * @param {*} dateFormatTo -> date format to return | default: 'YYYY-MM-DD HH:mm:ss' # DB format / ISO 8601
 * @returns
 */
const returnValidDatetime = (
  dateValue,
  todayDateOnNull = false,
  dateFormatFrom = 'DD/MM/YYYY HH:mm:ss',
  dateFormatTo = 'YYYY-MM-DD HH:mm:ss'
) => {
  let validDate = null;
  Eif (dateValue) {
    Iif (moment(dateValue, dateFormatFrom).isValid()) {
      // Object is a valid date
      validDate = moment(dateValue, dateFormatFrom).format(dateFormatTo);
      if (validDate) return validDate;
    } else {
      // String is a valid date
      validDate = moment(dateValue).format(dateFormatTo);
      Eif (validDate) return validDate;
    }
  }
 
  if (todayDateOnNull) {
    // Return formatted today date
    return moment().format(dateFormatTo);
  }
  return null;
};
 
export default {
  returnValidDatetime,
};