无法在JS中将DateDtring()应用于Date

问题描述 投票:1回答:1

我遇到了一个我想要了解的问题。我只是想通过使用toDateString()将日期转换为更易于阅读的格式。但是,这样做我得到一个“toDateString()不是函数”错误。

我可以使用toString()来做到这一点:

truncateDate() {
    if (this.employee && this.employee.dob)
    {
        let birthDate = this.employee.dob;
        console.log(birthDate); // 2011-06-12T05:00:00.000Z Prints to console
        console.log(birthDate.toString());
    }
}

但我不能做toDateString():

truncateDate() {
    if (this.employee && this.employee.dob)
    {
        let birthDate = this.employee.dob;
        console.log(birthDate); // 2011-06-12T05:00:00.000Z Prints to console
        console.log(birthDate.toDateString());
    }
}

我在这里错过了什么?

javascript typescript datetime
1个回答
4
投票

将字符串转换为Date Object,然后您就可以使用该函数。这是MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString

this.employee={}
this.employee.dob='1/2/2018'
let birthDate = this.employee.dob;
console.log(birthDate);
console.log(new Date(birthDate).toDateString());

//
© www.soinside.com 2019 - 2024. All rights reserved.