66

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
Syscall
  • 19,327
  • 10
  • 37
  • 52
udaya
  • 9,598
  • 15
  • 48
  • 67

7 Answers7

65

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.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
64

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.

LuckyLikey
  • 3,504
  • 1
  • 31
  • 54
  • 3
    yep, exactly my issue is well. Just another thing to add to the "reasons why JS sucks" – Noel Oct 27 '20 at 03:34
  • 1
    Yea not the best error message in history. Anyway in hindsight, I'd propably rephrase my answer a little. Apparently using typescript interfaces in angular does nothing, but hide the json data object behind the interface. That's why the date string won't be converted to a proper date format by itself. – LuckyLikey Oct 28 '20 at 07:21
12

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

Vikas Yadav
  • 3,094
  • 2
  • 20
  • 21
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
6

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);
Ryan Doherty
  • 38,580
  • 4
  • 56
  • 63
2

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

Date.parse(dat1) 

instead of

dat1.getTime()
Salman
  • 191
  • 9
0

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

Gülsen Keskin
  • 657
  • 7
  • 23
0

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

var d0 = yourDate.toString();
var d1 = new Date(Date.parse(d0));
SAAD BELEFQIH
  • 352
  • 3
  • 8