如何仅使用打字稿将日期格式 'dd/MM/yyyy' 的字符串转换为键入日期

how to convert string of date format 'dd/MM/yyyy' to type date only using typescript

我已尝试使用以下代码将日期从 'yyyy-mm-dd' 格式转换为 'dd/MM/yyyy'。 但是当我检查 typeof() 结果时,它是字符串类型。 有什么方法可以将其转换为唯一日期吗?

let result;
const timestamp = Date.parse(myStringDate)
if (isNaN(timestamp) === false) {
  const newdate = new Date(myStringDate);
 result = `${newdate.getDate()}/${newdate.getMonth()+1}/${newdate.getFullYear()}`
  return result;
} else {
  return myStringDate;
}

你可以试试这个:

const [year, month, day]: string[] = myStringDate.split('-');
const awesomeDate = `${day}/${month}/${year}`;

如果您不想用日期来计算某些东西,我会寻找格式正确的日期来使用 moment.js,这将允许您使用任何格式。