creationDate.getTime is not a function when comparing dates

Viewed 34

I'm trying to create a function which returns the number of days that has elapsed. Currently, the test is passing but also failing.

This is my function inside a class called application.service.ts

  private getElapsedDays(creationDate: Date) {
    const creationTime = creationDate.getTime();
    const currentTime = new Date().getTime();
    const elapsedTime = currentTime - creationTime;
    return Math.ceil(elapsedTime / (1000 * 60 * 60 * 24));
  }

And this is the test inside application.service.spec.ts

describe("getElapsedDays", () => {
  test("returns correct elapsed days", () => {
    const oneWeekAgo = new Date();
    oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);

    const elapsedDays = applicationService["getElapsedDays"](oneWeekAgo);

    expect(elapsedDays).toBe(7);
  });
});

so basically this test suite is running fine and passing strangely enough (it returns the number 7), but I'm still getting an error for the actual function itself.

TypeError: creationDate.getTime is not a function

       99 | 
      100 |   private getElapsedDays(creationDate: Date) {
    > 101 |     const creationTime = creationDate.getTime();
          |                                       ^
      102 |     const currentTime = new Date().getTime();
      103 |     const elapsedTime = currentTime - creationTime;
      104 |     return Math.ceil(elapsedTime / (1000 * 60 * 60 * 24));

Any help would be appreciated!

2 Answers

try using this:

describe("getElapsedDays", () => {
  test("returns correct elapsed days", () => {
    const date = new Date();
    const oneWeekAgo = new Date(date.getFullYear(), date.getMonths(), date.getDate() - 7);

    const elapsedDays = applicationService["getElapsedDays"](oneWeekAgo);

    expect(elapsedDays).toBe(7);
  });
});

I managed to get it to work. So I'm working with Typescript but just casting the Date type to creationDate does make an instance of it. Instead I had to wrap it around a new new Date()

So this is what worked for me and passed all the tests.

  private getElapsedDays(creationDate: Date) {
    const creationTime = new Date(creationDate).getTime();
    const currentTime = new Date().getTime();
    const elapsedTime = currentTime - creationTime;
    return Math.floor(elapsedTime / (1000 * 60 * 60 * 24));
  }
Related