Why javascript getTime() is not a function?

前端 未结 4 1723
夕颜
夕颜 2020-12-29 18:31

I used the following function,

function datediff()
{
 var dat1 = document.getElementById(\'date1\').value;
 alert(dat1);//i get 2010-04-01
var dat2 = documen         


        
4条回答
  •  鱼传尺愫
    2020-12-29 18:57

    For all those who came here and did indeed use Date typed Variables, here is the solution I found. It does also apply to TypeScript.

    I was facing this error because I tried to compare two dates using the following Method

    var res = dat1.getTime() > dat2.getTime(); // or any other comparison operator
    

    However Im sure I used a Date object, because Im using angularjs with typescript, and I got the data from a typed API call.

    Im not sure why the error is raised, but I assume that because my Object was created by JSON deserialisation, possibly the getTime() method was simply not added to the prototype.

    Solution

    In this case, recreating a date-Object based on your dates will fix the issue.

    var res = new Date(dat1).getTime() > new Date(dat2).getTime()
    

    Edit:

    I was right about this. Types will be cast to the according type but they wont be instanciated. Hence there will be a string cast to a date, which will obviously result in a runtime exception.

    The trick is, if you use interfaces with non primitive only data such as dates or functions, you will need to perform a mapping after your http request.

    class Details {
        description: string;
        date: Date;
        score: number;
        approved: boolean;
    
        constructor(data: any) {
          Object.assign(this, data);
        }
    }
    

    and to perform the mapping:

    public getDetails(id: number): Promise
    { return this.http .get
    (`${this.baseUrl}/api/details/${id}`) .map(response => new Details(response.json())) .toPromise(); }

    for arrays use:

    public getDetails(): Promise {
        return this.http
                   .get
    (`${this.baseUrl}/api/details`) .map(response => { const array = JSON.parse(response.json()) as any[]; const details = array.map(data => new Details(data)); return details; }) .toPromise(); }

    For credits and further information about this topic follow the link.

提交回复
热议问题