0

I have several dates (strings) that I want to convert to date objects.

const parse = (val, fmt) =>
{
    if (!val)
        return;
    const fn = (str, len) => val.substr(fmt.indexOf(str), len);

    return new Date(
        fn('YYYY', 4),
        fn('MM', 2) - 1,
        fn('DD', 2)
    );
};

console.log(parse('05/11/1896', 'DD/MM/YYYY')); // 1896-11-05
console.log(parse('07-12-2000', 'DD-MM-YYYY')); // 2000-12-07
console.log(parse('07:12:2000', 'DD:MM:YYYY')); // 2000-12-07
console.log(parse('2017/06/3', 'YYYY/MM/DD')); // 2017-06-03
console.log(parse('2017-06-15', 'YYYY-MM-DD')); // 2017-06-15
console.log(parse('2015 06 25', 'YYYY MM DD')); // 2015-06-25
However, I want to have a shorter format string, possibly as short as mdy. Can this be done?

I also want to support months or days without a leading zero; so 5/5/2021 instead of 05/05/2021.

Thanks.

1
  • "Can this be done?" Yes, there are many parsers and formatters to chose from. Writing one isn't particularly difficult, though a little tedious. Do you have a coding question? Commented Sep 16, 2021 at 20:23

1 Answer 1

0

This is what I came up with.

  • It uses as regular expression to remove any characters from the format, then makes each character unique using the method outlined here.
  • It then splits the input string based on another regex that finds the first non numerical character.
  • It finally has the correct values to send to the Date object.

const parse = (val, fmt) =>
{
    if (!val)
        return;
    fmt = Array.from(new Set(fmt.toLowerCase().replace(/[^dmy]/g, ''))).join('');
    const components = val.split(val.match(/[^0-9]/)[0]);
    let day = 1, month = 0, year, i = -1;
    while (i++ < 3)
        switch (fmt[i])
        {
            case 'd':
                day = components[i];
                break;
            case 'm':
                month = components[i] - 1;
                break;
            case 'y':
                year = components[i];
        }

    return new Date(year, month, day);
};

console.log(parse('05/11/1896', 'DD/MM/YYYY')); // 1896-11-05
console.log(parse('07-12-2000', 'DD-MM-YYYY')); // 2000-12-07
console.log(parse('07:12:2000', 'DD:MM:YYYY')); // 2000-12-07
console.log(parse('2017/6/3', 'YYYY/MM/DD')); // 2017-06-03
console.log(parse('2017-6-15', 'YYYY-MM-DD')); // 2017-06-15
console.log(parse('2015 6 25', 'YYYY MM DD')); // 2015-06-25
console.log(parse('2015 6 25', 'YyYy MM DD')); // 2015-06-25
console.log(parse('2015 6 25', 'Y-M-D')); // 2015-06-25
console.log(parse('2015 6 25', 'YYMD')); // 2015-06-25

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.