How can you separate the date and time from the string?

  • 0
    There is a conditional string '01 02 03 04 05 '. How from it can be distinguished as the date '01 02 03 ', and '04 05' as the time (04:05). But the string can be, for example, in such formats '01 02 2003 04 05 ', '01 / 02/03 04 05', '01 -02-03 04-05 'or in general '01 02 03', i.e. here in general only date (no time). Can this be implemented in moment js? And if not, what is the best way to implement it in JS?
    JavaScript Anonymous, Nov 9, 2020

  • 1 Answers
  • 0
    const parseToDate = string => {
    const [day, month, year, hour, minute] = string.match(/\d+/g).map(match => parseInt(match));
    const normalizedYear = year < 2000 && year.toString().length <= 2 ? year + 2000 : year;
    const date = new Date(normalizedYear, month - 1, day, hour || 0, minute || 0);

    return date;
    };

    const strings = [
    '01 02 2003 04 05',
    '01 02 03 04 05',
    '01/02/03 04 05',
    '01-02-3 04-05',
    '23-08/2019 3 4',
    '1 1 1980 0 0',
    '2 2 0'
    ];

    for (const string of strings) {
    const date = parseToDate(string);

    console.log(date.toLocaleString());
    }

    /**
    '01.02.2003, 04:05:00'
    '01.02.2003, 04:05:00'
    '01.02.2003, 04:05:00'
    '01.02.2003, 04:05:00'
    '23.08.2019, 03:04:00'
    '01.01.1980, 00:00:00'
    '02.02.2000, 00:00:00'
    */
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!