bobbyache

Seconds to Duration

Jan 8th, 2020
784
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. https://stackoverflow.com/questions/37096367/how-to-convert-seconds-to-minutes-and-hours-in-javascript
  2.  
  3. function secondsToHms(d) {
  4.     d = Number(d);
  5.     var h = Math.floor(d / 3600);
  6.     var m = Math.floor(d % 3600 / 60);
  7.     var s = Math.floor(d % 3600 % 60);
  8.  
  9.     var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
  10.     var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
  11.     var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
  12.     return hDisplay + mDisplay + sDisplay;
  13. }
  14.  
  15.  
  16.  
  17. class TimeDuration {
  18.     private totalSeconds: number = 0;
  19.  
  20.     constructor(totalSeconds: number = 0) {
  21.         this.totalSeconds = totalSeconds;
  22.     }
  23.  
  24.     get TotalSeconds(): number {
  25.         return this.totalSeconds;
  26.     }
  27.     set TotalSeconds(totalSeconds: number) {
  28.         this.totalSeconds = totalSeconds;
  29.     }
  30.  
  31.     get Hours(): number {
  32.         return Math.floor(this.totalSeconds / 3600);
  33.     }
  34.     get Minutes(): number {
  35.         return Math.floor(this.totalSeconds % 3600 / 60);
  36.     }
  37.     get Seconds(): number {
  38.         return Math.floor(this.totalSeconds % 3600 % 60);
  39.     }
  40.  
  41.     get ToText(): string {
  42.         const h = this.Hours;
  43.         const m = this.Minutes;
  44.         const s = this.Seconds;
  45.  
  46.         var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
  47.         var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
  48.         var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
  49.  
  50.         return hDisplay + mDisplay + sDisplay;
  51.     }
  52.  
  53.     public AddHours(hours: number): void {
  54.         this.TotalSeconds += hours * 3600;
  55.     }
  56.     public AddMinutes(minutes: number): void {
  57.         this.TotalSeconds += minutes * 60;
  58.     }
  59.  
  60.     public AddSeconds(seconds: number): void {
  61.         this.TotalSeconds += seconds;
  62.     }
  63. }
  64.  
  65. const timeDuration = new TimeDuration(300);
  66. // timeDuration.TotalSeconds = 3030;
  67.  
  68. console.log(timeDuration.TotalSeconds);
  69. console.log(timeDuration.Hours);
  70. console.log(timeDuration.Minutes);
  71. console.log(timeDuration.Seconds);
  72. console.log(timeDuration.ToText);
  73.  
  74. timeDuration.AddHours(1);
  75.  
  76. console.log(timeDuration.ToText);
  77.  
  78. timeDuration.AddMinutes(1);
  79.  
  80. console.log(timeDuration.ToText);
  81.  
  82. timeDuration.AddSeconds(1);
  83.  
  84. console.log(timeDuration.ToText);
Advertisement
Add Comment
Please, Sign In to add comment