打字稿日期格式

use*_*394 2 typescript

我正在使用 Angular 2/4 如何将日期格式化为
2017-10-03T14:51:06.078Z

下面是我的代码:

  public today: number = Date.now();
 console.log("today time " +this.today);
Run Code Online (Sandbox Code Playgroud)

我尝试添加

this.today.toLocaleString()
Run Code Online (Sandbox Code Playgroud)

这似乎不起作用

小智 5

你可以这样做

this.todayDate = new Date();
this.dateToday = (this.todayDate.getFullYear() + '-' + ((this.todayDate.getMonth() + 1)) + '-' + this.todayDate.getDate() + ' ' +this.todayDate.getHours() + ':' + this.todayDate.getMinutes()+ ':' + this.todayDate.getSeconds());
Run Code Online (Sandbox Code Playgroud)

您可以检查控制台日志,

console.log('today date', this.dateToday);
Run Code Online (Sandbox Code Playgroud)

输出将是

today date 2017-10-3 10:38:10
Run Code Online (Sandbox Code Playgroud)

解释:“this.dateToday”是一个any类型的变量,它将根据需要存储日期。

您还需要获取单独的年、月、日期和时间并将其连接在一起。您可以在线或在 IDE 中查看更多日期方法。