G
G
Gregory2018-03-30 16:44:40
JavaScript
Gregory, 2018-03-30 16:44:40

Convert string to date?

How can a string of this type be converted to a date with time so that the data can be sorted? Interested in a solution without using third-party plugins and libraries.
let time = "06:56 30.3.18"

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Shvets, 2018-03-30
@Groyreg

const time = "06:56 30.3.18"

function parseDate(dateString) {
    if (!dateString) return new Date();
    const regexp = /(\d+):(\d+)\s(\d+).(\d+).(\d+)/;
    if(!regexp.test(dateString)) throw new Error('date string format error');
    const d =regexp.exec(dateString);
    if (d[5].length == 2) d[5] = `20${d[5]}`;
    return new Date(d[5], d[4] - 1, d[3], d[1], d[2]);
}

const date1 = new Date(2018, 2, 30, 6, 56);
const date2 = parseDate(time);

console.assert(date1.getTime() == date2.getTime());

R
RidgeA, 2018-03-30
@RidgeA

This is an invalid date format.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question