1

I have a string to parse into Date

const a = '18122122'

and this way(constantly using substr) to parse it is ugly and error-prone

const date = new Date('20' + a.substr(0, 2), a.substr(2, 2) - 1, a.substr(4, 2), a.substr(6,2 ))

Do I miss a method like

const dateArray = a.<method>(2) // return ['18', '12', '21', '22']
dateArray[0] = '20' + dateArray[0]
dateArray[1] -= 1;
const date = new Date(...dateArray)

2 Answers 2

3

You can use a global regular expression to match repeated instances of 2 digits, and then replace the array items as needed:

const a = '18122122';
const dateArray = a.match(/\d{2}/g);
dateArray[0] = '20' + dateArray[0];
dateArray[1] -= 1;
const date = new Date(...dateArray);
console.log(date);

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

Comments

1

Try:

const a = "18042019";
let [, day, month, year] = a.match(/^(\d{2})(\d{2})(\d{4})/);
new Date(year, --month, day);

It doesn't matter that the Date arguments are strings containing numbers, as the constructor will typecast each parameter to a Number anyway.

1 Comment

Yes, and I got the order of parameters wrong because I was reading your input back-the-front. Pro tip: when posting examples, it really, really helps to use a realistic example instead of key-mashing.

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.