我有一个'20180715'
对象附带的JSON响应,我需要将string
转换为date
,例如:
let dateString = '20180715';
我尝试过日期testdate = new Date (dateString);
//失败。
如何在TypeScript中将其转换为日期对象?
谢谢!
答案 0 :(得分:6)
如果字符串中日期的实际结构不变,则只需使用.substr
函数即可获取字符串的各个部分
请记住,month is 0-based(因此月份必须减少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());
答案 1 :(得分:3)
您还可以使用RegEx进行解析。请注意,月份的递减运算符(--
),因为Date将月份的索引值定为0。有关更高级的内容,请参考moment.js,其中包括许多格式模板。
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);
}