Why JavaScript getTime() is not a function?
Asked Answered
B

7

70

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
Billet answered 13/4, 2010 at 7:12 Comment(0)
G
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.

Gerdi answered 13/4, 2010 at 7:15 Comment(0)
W
74

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.

Wilonah answered 22/10, 2018 at 14:15 Comment(2)
yep, exactly my issue is well. Just another thing to add to the "reasons why JS sucks"Frederico
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.Wilonah
G
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.

Gerdi answered 13/4, 2010 at 7:15 Comment(0)
C
13

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

Cavazos answered 13/4, 2010 at 7:14 Comment(0)
B
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);
Buine answered 13/4, 2010 at 7:15 Comment(3)
I woud say that it should be var date = new Date(Date.parse(dat1));Fragment
@Hexodus: Why is that?Sanjak
@EdS. You're right - Both ways will produce the same result so one should use Rayan's solution because it's shorter.Fragment
W
2

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

Date.parse(dat1) 

instead of

dat1.getTime()
Webby answered 25/2, 2022 at 14:56 Comment(0)
F
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

Fionafionna answered 8/9, 2022 at 8:15 Comment(0)
D
0

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

var d0 = yourDate.toString();
var d1 = new Date(Date.parse(d0));
Devinne answered 25/4, 2023 at 19:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.