Parses a given string to a date object, e.g. 2000-01 and 2011-11-01 or 2005. - Node.js String

Node.js examples for String:Parse

Description

Parses a given string to a date object, e.g. 2000-01 and 2011-11-01 or 2005.

Demo Code


/**//from   w  ww . j  a v  a 2s  . com
 * @ngdoc function
 * @name parseDate
 * @function
 * @param {string} pDate - date to be parsed
 *
 * @description
 * Parses a given string to a date object, e.g. 2000-01 and 2011-11-01 or 2005.
 * Returns a date object or null if string size is less 4.
 */
function parseDate(pDate) {
    var date;
    if (typeof pDate === 'date') {
        return pDate;
    } else {
        if (pDate && pDate.length >= 4) {
            date = new Date();
            if (pDate.length == 4) {
                date.setFullYear(pDate);
                date.setMonth(0);
                date.setDate(1);
            } else {
                // 2000-01
                if (pDate.length == 7) {
                    var inputDate = pDate.split("-", 2);
                    date.setFullYear(inputDate[0]);
                    date.setMonth(inputDate[1]);
                    date.setDate(1);
                } else {
                    // 2000-01-01
                    if (pDate.length == 10) {
                        var inputDate = pDate.split("-", 3);
                        date.setFullYear(inputDate[0]);
                        date.setMonth(inputDate[1]);
                        date.setDate(inputDate[2]);
                    } else {
                        date = new Date(pDate);
                    }
                }
            }
        }
    }
    return date;
}

Related Tutorials