最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - String to date in TypeScript - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 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());

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

发布评论

评论列表(0)

  1. 暂无评论