String to date in TypeScript
18,861
Solution 1
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());
Solution 2
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);
}
Related videos on Youtube
Author by
Radha Krishna
Updated on May 28, 2022Comments
-
Radha Krishna almost 2 years
I have a JSON response coming with the object of
'20180715'
and I need to convert thatstring
todate
, 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!
-
Radha Krishna almost 6 yearsThank you Rick! Yes the structure of the date string will be same. That works perfect! Thanks.
-
Salman A almost 6 yearsThis is an abuse of post decrement operator.
RegExp.$2 - 1
is much better. -
vol7ron over 5 years@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.