Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot Apply toDateString() to Date in JS

I am running into a problem I'm trying to understand. I am simply trying to convert a date into a more reader-friendly format by using toDateString(). However, in doing so I am getting a "toDateString() is not a function" error.

I can do this, using 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());
    }
}

But I cannot do 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());
    }
}

What am I missing here?

like image 275
Rey Avatar asked Jan 02 '23 23:01

Rey


1 Answers

Convert the string to Date Object then you will be able to use that function. Here is 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());

//
like image 100
sumeet kumar Avatar answered Jan 05 '23 14:01

sumeet kumar