Search code examples
htmldatepickerng-bootstrapngmodelangular12

How to Create Date Count timer selecting date from the date picker input and show the difference of selected date to current date


** This is My Typescript file **

        import { Component, OnInit } from '@angular/core';
        import { interval, Subscription } from 'rxjs';

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

       model = new Date() //'2021 08 12  00:00:00'
       constructor() { }

       private timeinterval = interval
       private subscription!: Subscription;

       public dateNow = new Date();
       public dDay = this.model.getTime();
       milliSecondsInASecond = 1000;
       hoursInADay = 24;
       minutesInAnHour = 60;
       SecondsInAMinute  = 60;

      public timeDifference: any;
      public secondsToDday:any;
      public minutesToDday:any;
      public hoursToDday:any;
      public daysToDday:any;


      private getTimeDifference () {
          this.timeDifference = this.dDay - new  Date().getTime();
          this.allocateTimeUnits(this.timeDifference);
     }

     private allocateTimeUnits (timeDifference: any) {
        this.secondsToDday = Math.floor((timeDifference) / 
        (this.milliSecondsInASecond) 
         % this.SecondsInAMinute);
         this.minutesToDday = Math.floor((timeDifference) / 
       (this.milliSecondsInASecond * 
        this.minutesInAnHour) % this.SecondsInAMinute);
       this.hoursToDday = Math.floor((timeDifference) / (this.milliSecondsInASecond * 
        this.minutesInAnHour * this.SecondsInAMinute) % this.hoursInADay);
        this.daysToDday = Math.floor((timeDifference) / (this.milliSecondsInASecond * 
        this.minutesInAnHour * this.SecondsInAMinute * this.hoursInADay));
   }

    ngOnInit() {
        this.stratInterval();
   }

    ngOnDestroy() {
        this.subscription.unsubscribe();
   }
   stopInterval(){
       this.subscription.unsubscribe();
  }
    stratInterval(){
       this.subscription = this.timeinterval(1000)
      .subscribe(x => { this.getTimeDifference(); });
  }

}

  • When I run the app then by default date (current date) is loaded and shown and when i select the other date i could not change in my count down timer html file it still defulat value of date picker but i want to select the date and start count down of the date from the selected date to current date *

** This is My Html File **

  <div class="container">
       <h1 class="text-success">Date Picker App</h1>
        <form class="form-inline">
            <div class="form-group">
                <div class="input-group">
                    <input class="form-control" placeholder="yyyy-mm-dd"
                       name="dp" [(ngModel)]="model" ngbDatepicker 
                        #d="ngbDatepicker">
                     <div class="input-group-append">
                        <button class="btn btn-outline-secondary calendar" 
                       (click)="d.toggle()" type="button"></button>
                     </div>
               </div>
           </div>
      </form>   
 </div>

 <!--Count Down Timer DIsplay -->

   <div class="container mt-5">
  
       <div class="timer" *ngIf="model">
           <h2>Time Left</h2>
           <span id="days"> {{daysToDday}} </span> Day(s)
           <span id="hours"> {{hoursToDday}} </span>Hrs 
           <span id="minutes"> {{minutesToDday}} </span>Min
           <span id="seconds"> {{secondsToDday}} </span>S <br>
           <div class="mt-3">
               <button  (click)="stopInterval()" class="btn btn-danger btn- 
               sm">Stop</button>
               <button  (click)="stratInterval()" class="btn btn-info btn-sm 
               "id="resetbtn">Restart</button>
          </div>
     </div>
 </div>

** I Have Tried Many Options and Logics but Its not Working Please Anyone can Guide me How I can Implement This **

** This is the Screenshot of Result ** enter image description here


Solution

  • The problem is that your getTimeDifference function calculated the time difference based on dDay:

    this.timeDifference = this.dDay - new Date().getTime();
    

    but dDay is only ever set once (where the variable is declared):

    public dDay = this.model.getTime();
    

    When a new date is chosen in the date picker, the variable model is updated but dDay is never updated and it's value is the original date. If you add the following line to your getTimeDifference function:

    this.dDay = this.model.getTime();
    

    then dDay will get updated with the new date after one is selected. The getTimeDifference function becomes:

    private getTimeDifference() {
      this.dDay = this.model.getTime(); // new line to update dDay
      this.timeDifference = this.dDay - new Date().getTime();
      this.allocateTimeUnits(this.timeDifference);
    }
    

    Please see this StackBlitz for a demo. Now when you select a new date, the countdown timer gets updated accordingly.