Answer the question
In order to leave comments, you need to log in
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
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());
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question