June 20, 2022

Convert seconds to hh-mm-ss with JavaScript/TypeScript

I received this requirement while working on Angular application and developing the two-factor authentication screen with SMS OTP. This screen has the timer countdown to show remaining time in seconds (in mm:ss format) to enable the button to resend OTP.

I found two different functions to format the seconds in hh:mm:ss format.

In first method, you can manually perform the arithmetic operations to extract hours, minutes and seconds from given value.

Convert_Seconds_To_HHMMSS(seconds) {

      let hour = Math.floor(seconds / 3600);
      let minute = Math.floor((seconds % 3600) / 60);
      let second = seconds % 60;

      if(hour.toString().length === 1) {
            hour = `0${hour}`;
      }
      if(minute.toString().length === 1) {
            minute = `0${minute}`;
      }
      if(second.toString().length === 1) {
            second = `0${second}`;
      };

      let timeFormatted = `${hour}-${minute}-${second}`;

      return timeFormatted;
}

In second method, you can use one-liner solution using Date.toISOString() function.

new Date(seconds * 1000).toISOString().substring(11, 16)

If the seconds value is less than 3600 (less than an hour) or you don't want t show the hours in formatted string, and only need to show minutes and seconds (mm:ss), then simply change the arguments for substring() function to extract the required string part.

new Date(seconds * 1000).toISOString().substring(14, 19)

No comments:

Post a Comment