在研发过程中,经常会Date与字符串的转换,下面的代码示例实现将年-月-日格式的字符串转为Date对象
function strToDate(dateStr: string): Date {
const dates = dateStr.split("-");
const year = parseInt(dates[0]);
const month = parseInt(dates[1]) - 1; // 月份从0开始
const day = parseInt(dates[2]);
return new Date(year, month, day);
}
调用代码示例
let date:Date = strToDate("2008-09-08"); // date 2008-08-08 00:00:00