udaya
udaya

Reputation: 9778

Why JavaScript getTime() is not a function?

I used the following function:

function datediff()
{
  var dat1 = document.getElementById('date1').value;
  alert(dat1);//i get 2010-04-01
  var dat2 = document.getElementById('date2').value;
  alert(dat2);// i get 2010-04-13
 
  var oneDay = 24*60*60*1000;   // hours*minutes*seconds*milliseconds
  var diffDays = Math.abs((dat1.getTime() - dat2.getTime())/(oneDay));
  alert(diffDays);
}

I get the error:

dat1.getTime()` is not a function

Upvotes: 71

Views: 232536

Answers (7)

SAAD BELEFQIH
SAAD BELEFQIH

Reputation: 372

solution : we can convert yourdate to String then call Date.parse() method.

var d0 = yourDate.toString();
var d1 = new Date(Date.parse(d0));

Upvotes: 0

Gülsen Keskin
Gülsen Keskin

Reputation: 800

You could conditionally check if the value is a Date object in the following way.

const d1 = new Date();

if (typeof d1 === 'object' && d1 !== null && 'getTime' in d1) {
  const result = d1.getTime();
  console.log(result); // 👉️ 163966...
}

https://bobbyhadz.com/blog/javascript-typeerror-date-gettime-is-not-a-function

Upvotes: 0

Salman
Salman

Reputation: 669

It's a time format problem change it by following.

Date.parse(dat1) 

instead of

dat1.getTime()

Upvotes: 2

LuckyLikey
LuckyLikey

Reputation: 3840

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<Details> {
    return this.http
               .get<Details>(`${this.baseUrl}/api/details/${id}`)
               .map(response => new Details(response.json()))
               .toPromise();
}

for arrays use:

public getDetails(): Promise<Details[]> {
    return this.http
               .get<Details>(`${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.

Upvotes: 80

Haim Evgi
Haim Evgi

Reputation: 125526

To use this function/method,you need an instance of the class Date .

This method is always used in conjunction with a Date object.

See the code below :

var d = new Date();
d.getTime();

Link : http://www.w3schools.com/jsref/jsref_getTime.asp

Upvotes: 13

Ryan Doherty
Ryan Doherty

Reputation: 38740

dat1 and dat2 are Strings in JavaScript. There is no getTime function on the String prototype. I believe you want the Date.parse() function: http://www.w3schools.com/jsref/jsref_parse.asp

You would use it like this:

var date = Date.parse(dat1);

Upvotes: 6

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827496

That's because your dat1 and dat2 variables are just strings.

You should parse them to get a Date object, for that format I always use the following function:

// parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}

I use this function because the Date.parse(string) (or new Date(string)) method is implementation dependent, and the yyyy-MM-dd format will work on modern browser but not on IE, so I prefer doing it manually.

Upvotes: 65

Related Questions