I have a JSON response ing 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!
I have a JSON response ing 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!
Share Improve this question edited Jul 16, 2018 at 1:39 Rick 4,1269 gold badges27 silver badges37 bronze badges asked Jul 15, 2018 at 19:49 Radha KrishnaRadha Krishna 431 gold badge1 silver badge5 bronze badges2 Answers
Reset to default 7If 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());
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);
}