TimesHelper.ts 1.1 KB

123456789101112131415161718192021222324252627282930313233
  1. export class CountdownTimer {
  2. private _timerID = -1;
  3. start(seconds: number, onUpdate: (left: number) => void, interval = 1) {
  4. this.stop();
  5. if (seconds <= 0) return;
  6. const end_ts = Date.now() + seconds * 1000;
  7. const update = () => {
  8. const left = Math.floor((end_ts - Date.now()) / 1000);
  9. onUpdate && onUpdate(left);
  10. }
  11. this._timerID = setInterval(update, interval * 1000);
  12. update();
  13. }
  14. stop() {
  15. if (this._timerID > -1) {
  16. clearInterval(this._timerID);
  17. }
  18. this._timerID = -1;
  19. }
  20. }
  21. export function formatTimes(seconds: number): string {
  22. const totalSeconds = Number.isFinite(seconds) ? Math.max(0, Math.floor(seconds)) : 0;
  23. const days = Math.floor(totalSeconds / 86_400);
  24. const hours = Math.floor((totalSeconds % 86_400) / 3_600);
  25. const minutes = Math.floor((totalSeconds % 3_600) / 60);
  26. const remainingSeconds = totalSeconds % 60;
  27. const pad = (value: number) => value.toString().padStart(2, '0');
  28. return `${days}D ${pad(hours)}:${pad(minutes)}:${pad(remainingSeconds)}`;
  29. }