【问题标题】:Typescript date formatting打字稿日期格式
【发布时间】:2017-10-03 16:23:56
【问题描述】:

我正在使用角度 2/4 我怎样才能把日期格式化成这个
2017-10-03T14:51:06.078Z

下面是我的代码:

  public today: number = Date.now();
 console.log("today time " +this.today);

我尝试添加

this.today.toLocaleString()

好像没用

【问题讨论】:

标签: typescript


【解决方案1】:

你应该使用 toISOString 方法:

this.today.toISOString();

但你需要将类型从数字更改为日期:

namespace Testing {
    export class Test {
        public today: Date;

        constructor() {
            this.today = new Date();
            console.log(this.today.toISOString());
        }
    }
}

更多信息可以找到here

【讨论】:

  • 我试过你的代码它没有工作 console.log("今天时间" +this.today.toISOString());我收到错误
  • 你今天选对了吗?你得到什么编译错误?
【解决方案2】:

你可以这样做

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

您可以查看控制台日志,

console.log('today date', this.dateToday);

输出将是

today date 2017-10-3 10:38:10

说明: "this.dateToday" 是 any 类型的变量,它将根据需要存储日期。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多