N
N
NatP2018-08-24 11:15:45
typescript
NatP, 2018-08-24 11:15:45

How to get difference between dates in typescript in milliseconds for reverse time count?

task: countdown to a specific date, using setInterval, but it is not possible to get the difference between dates, due to

TS2362 The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum

and the countdown does not start

import {Component, Input, OnInit, OnDestroy} from '@angular/core';


@Component({
  selector: 'app-summer-counter',
  templateUrl: './summer-counter.component.html',
  styleUrls: ['./summer-counter.component.css']
})
export class SummerCounterComponent implements OnInit, OnDestroy {

  currentDate: Date = new Date();
  endDate: Date = new Date(2018, 8, 1, 1, 0, 0);
  difdate: number = 0;
  sec: number = 0;
  min: number = 0;
  ours: number = 0;
  days: number = 0;

  constructor() {
  }

  ngOnInit() {
    this.difdate = setInterval(() => this.endDate - this.currentDate, 1000);
    this.sec = setInterval(() => this.difdate / 1000, 1000);
    this.min = setInterval(() => this.sec * 60, 1000);
    this.ours = setInterval(() => this.min * 60, 1000);
    this.days = setInterval(() => this.ours * 24, 1000);

  }

  ngOnDestroy(): void {
    clearInterval(this.difdate);
    clearInterval(this.sec);
    clearInterval(this.min);
    clearInterval(this.ours);
    clearInterval(this.days);
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Shvets, 2018-08-24
@Xuxicheta

setInterval returns an intervalID, not the result of the callback. And you are trying to divide intervalID by a number.
And TS swears right. This is what he needs - to point out errors at the stage of writing the code.

0
0xD34F, 2018-08-24
@0xD34F

TS2362 The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum

Well, yes. It is necessary to convert dates to numbers when subtracting, i.e., instead of let it be , for example. Well, in general, what you are doing is just crazy nonsense. Why do you need five different intervals? What are you trying to do in the callbacks of these intervals? - the results of your calculations fly away to nowhere. You say your goal is the countdown? Let me show you how it can look like, and you look and think what's what.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question