All files / src/app/components/countdown countdown.component.ts

92.68% Statements 38/41
83.33% Branches 10/12
87.5% Functions 7/8
92.3% Lines 36/39

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87                    96x   1x 1x 1x 1x 1x 1x 1x 1x           1x 1x 1x 56x 1x       3x 3x               60x 60x 59x   59x 59x       59x 59x 59x 59x     1x 1x 1x 1x         1472x     1472x       4x 3x   3x 3x     1x              
import { NgIf } from '@angular/common';
import { Component, Input, OnChanges, OnDestroy, OnInit } from '@angular/core';
import { interval, Subscription } from 'rxjs';
 
@Component({
  selector: 'app-countdown',
  imports: [NgIf],
  templateUrl: './countdown.component.html',
  styleUrl: './countdown.component.scss'
})
export class CountdownComponent implements OnInit, OnChanges, OnDestroy{
 
  @Input() targetTimestamp: number|null = null;
  days: number | null = null;
  hours: number | null = null;
  minutes: number | null = null;
  seconds: number | null = null;
  private subscription: Subscription | null = null;
  isPositiveTime = false;
  targetDate: Date | null = null;
  localTimeZone: string;
  localMonth: string;
  UTCMonth: string;
 
  ngOnInit() {
    this.targetTimestamp = null;
    this.updateTarget();
    this.updateTime();
    this.subscription = interval(100).subscribe(() => this.updateTime());
    this.localTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  }
 
  ngOnChanges(){
    this.updateTarget();
    this.updateTime();
  }
 
  ngOnDestroy() {
    this.subscription?.unsubscribe();
  }
 
  private updateTime() {
    const now = Math.floor(Date.now() / 1000);
    if (this.targetTimestamp !== null){
      let diff = this.targetTimestamp - now;
 
      this.isPositiveTime = diff < 0;
      Iif (this.isPositiveTime) {
        diff = -diff;
      }
 
      this.days = Math.floor(diff / 86400);
      this.hours = Math.floor((diff % 86400) / 3600);
      this.minutes = Math.floor((diff % 3600) / 60);
      this.seconds = Math.floor(diff % 60);
    }
    else{
      this.days = null;
      this.hours = null;
      this.minutes = null;
      this.seconds = null;
    }
  }
 
  formatNumber(value: number | null): string {
    Iif (value === null){
      return '--';
    }
    return value < 10 ? '0' + value : value.toString();
  }
 
  updateTarget(){
    if (this.targetTimestamp !== null){
      this.targetDate = new Date(this.targetTimestamp*1000);
 
      this.localMonth = this.targetDate.toLocaleString('en-US', { month: 'long' });
      this.UTCMonth = this.targetDate.toLocaleString('en-US', { month: 'long', timeZone: 'UTC' });
    }
    else{
      this.targetDate = null;
 
    }
 
  }
 
}