Skip to content
Advertisement

How to parse a date in format “YYYYmmdd” in JavaScript?

This is a noob question:

How to parse a date in format "YYYYmmdd" without external libraries ? If the input string is not in this format I would like to get invalid Date (or undefined if it will be easier).

Advertisement

Answer

function parse(str) {
    if(!/^(d){8}$/.test(str)) return "invalid date";
    var y = str.substr(0,4),
        m = str.substr(4,2),
        d = str.substr(6,2);
    return new Date(y,m,d);
}

Usage:

parse('20120401');

UPDATE:

As Rocket said, months are 0-based in js…use this if month’s aren’t 0-based in your string

function parse(str) {
    if(!/^(d){8}$/.test(str)) return "invalid date";
    var y = str.substr(0,4),
        m = str.substr(4,2) - 1,
        d = str.substr(6,2);
    return new Date(y,m,d);
}

UPDATE:

More rigorous checking for validity of date. Adopted HBP’s way to validate date.

function parse(str) {
    var y = str.substr(0,4),
        m = str.substr(4,2) - 1,
        d = str.substr(6,2);
    var D = new Date(y,m,d);
    return (D.getFullYear() == y && D.getMonth() == m && D.getDate() == d) ? D : 'invalid date';
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement