3

I have a JSON response coming with the object of '20180715' and I need to convert that string to date, for example:

let dateString = '20180715';

I tried Date testdate = new Date (dateString); //fails.

How can I convert it to a date object in TypeScript?

Thanks in advance!

2 Answers 2

7

If the actual structure of the date in the string doesn't change, you can just simply get the parts of the string using the .substr function.

Keep in mind, that the month is 0-based, hence the month have to be decreased by 1.

const dateString = '20180715';
const year = dateString.substr(0, 4);
const month = dateString.substr(4, 2) - 1;
const day = dateString.substr(6, 2);
const date = new Date(year, month, day);

console.log(date.toString());

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

1 Comment

Thank you Rick! Yes the structure of the date string will be same. That works perfect! Thanks.
3

You can also use RegEx to parse. Notice the decremental operator (--) for the month, since Date indexes the month at 0. For anything more advanced, please refer to moment.js, which includes many formatting templates.

const re  = /(\d{4})(\d{2})(\d{2})/;
const str = '20180715';
if (re.test(str)) {
  const dt = new Date(RegExp.$1, --RegExp.$2, RegExp.$3);
  console.log(dt);
}

2 Comments

This is an abuse of post decrement operator. RegExp.$2 - 1 is much better.
@SalmanA that would work too, but it is not an abuse of the post-operator, it is a pre-operator and this is one way it was intended to be used where order of operation is important. Other solutions, like yours, would also work — the decision to do so comes down to preference and styling guides.

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.