代码之家  ›  专栏  ›  技术社区  ›  Rey

无法将toDateString()应用于JS中的日期

  •  4
  • Rey  · 技术社区  · 7 年前

    我遇到了一个我正在努力理解的问题。我只是想通过使用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());
        }
    }
    

    我错过了什么?

    1 回复  |  直到 7 年前
        1
  •  9
  •   sumeet kumar    7 年前

    将字符串转换为日期对象,然后您将能够使用该函数。 这是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());
    
    //