Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
85
rated 0 times [  90] [ 5]  / answers: 1 / hits: 19941  / 6 Years ago, sun, july 15, 2018, 12:00:00

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!


More From » string

 Answers
16

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());




[#53975] Wednesday, July 11, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kristinsonjab

Total Points: 364
Total Questions: 98
Total Answers: 98

Location: Christmas Island
Member since Mon, Oct 19, 2020
4 Years ago
kristinsonjab questions
Fri, Mar 4, 22, 00:00, 2 Years ago
Fri, Jan 22, 21, 00:00, 3 Years ago
Fri, Aug 14, 20, 00:00, 4 Years ago
;