Change date format

/**
 * @description To format the Date Object into the given type/format
 * @param {Date} dateObj
 * @param {String} type
 * @returns {boolean|String}
 */
function formatDate(dateObj, type) {
    let dateAsKeys = splitDate(dateObj);
    if (dateAsKeys)
        switch (type) {
            case 'MM/DD/YYYY':
                ;
            case 'M/D/YYYY':
                return dateLogic.changeDateFormat(dateAsKeys, type, '/');
            case 'D/M/YYYY':
                ;
            case 'DD/MM/YYYY':
                return changeDateFormat(dateAsKeys, type, '/');
            case 'YYYY-MM-DD':
                return changeDateFormat(dateAsKeys, type, '-');
            default:
                return changeDateFormat(dateAsKeys, 'MM/DD/YYYY', '/');
        }
    ;
    return false;
}
/**
 * Take the Date Object and return it as {DD:value, MM:value, YYYY:value}
 * @param {Date} dateObj
 * @returns {boolean|{DD: (string|number), MM: string, D: number, YYYY: number, M: number}}
 */
function splitDate(dateObj) {
    return {
        D: dateObj.getDate(),
        DD: dateObj.getDate() < 10 ? ('0' + dateObj.getDate()) : dateObj.getDate(),
        M: dateObj.getMonth() + 1,
        MM: (dateObj.getMonth() + 1) < 10 ? ('0' + (dateObj.getMonth() + 1)) : (dateObj.getMonth() + 1),
        YYYY: dateObj.getFullYear()
    };
}
/**
 * check the dateAsKeys object contain the keys and return the date in given type/format
 * @param {Object<String, Number>} dateAsKeys
 * @param {String} type
 * @param {String} delimiter
 * @returns {string|boolean}
 */
function changeDateFormat(dateAsKeys, type, delimiter) {
    return type.split(delimiter).reduce(function (i, j) {
        return i.push(dateAsKeys[j]), i;
    }, []).join(delimiter);
}

Leave a comment

Your email address will not be published. Required fields are marked *