Seconds to minutes and hours javascript

Как конвертировать секунды в минуты и часы с помощью vanilla JS

Работать со временем в JavaScript может быть не простой. Сегодня я покажу вам, как конвертировать секунды в минуты и часы с помощью vanilla JS.

Конвертирование часов

Допустим, у вас была метка времени в секундах, которую вы хотели отобразить в HH:MM:SS формате.

60 секунд в минуту и ​​60 минут в час. Мы делим свой timestamp дважды на 60 . В результате мы получаем 2.6283 .

var timestamp = 9462; // 2.628333333 var hours = timestamp / 60 / 60;

Мы можем использовать Math.floor() для округления до ближайшего целого числа чтобы получить количество часов в int.

var timestamp = 9462; // 2 var hours = Math.floor(timestamp / 60 / 60);

Преобразование минут

В минуте есть 60 секунд. Давайте разделим наш timestamp на 60 и используем, Math.floor() чтобы округлить до ближайшего целого числа. Это вернет нам 157 , потому что это также включает в себя все минуты, которые в нашем hours .

var timestamp = 9462; // 2 var hours = Math.floor(timestamp / 60 / 60); // 157 var minutes = Math.floor(timestamp / 60);

Мы умножим наш hours на, 60 чтобы получить его значение в минутах, а затем вычтем его из нашего, minutes чтобы получить правильное значение.

var timestamp = 9462; // 2 var hours = Math.floor(timestamp / 60 / 60); // 37 var minutes = Math.floor(timestamp / 60) - (hours * 60);

Подсчет секунд

Наконец, давайте посчитаем секунды.

Читайте также:  Jar чем открыть java

Для этого, мы можем использовать оператор остатка от деления. Он возвращает сумму, оставшуюся после деления на число.

Мы будем использовать его для деления timestamp на 60 (количество секунд в минуте). Число, которое мы получаем, — это секунды после удаления всех минут.

var timestamp = 9462; // 2 var hours = Math.floor(timestamp / 60 / 60); // 37 var minutes = Math.floor(timestamp / 60) - (hours * 60); // 42 var seconds = timestamp % 60;

Форматирование времени

Теперь, когда у нас есть свои hours , minutes и seconds мы готовы отформатировать их в наш формат HH:MM:SS .

Мы можем для этого использовать простую конкатенацию строк.

// 2:37:42 var formatted = hours + ':' + minutes + ':' + seconds;

Это может быть достаточно хорошо, но что, если вы хотите вести 0 в hours ? Что если наши minutes или seconds однозначные числа?

Мы можем преобразовать наши числа в строки и использовать метод padStart() для обеспечения минимального количества цифр.

// 02:37:42 var formatted = [ hours.toString().padStart(2, '0'), minutes.toString().padStart(2, '0'), seconds.toString().padStart(2, '0') ].join(':');

Источник

How to Convert Seconds to Hours and Minutes in JavaScript

To convert seconds to hours and minutes in JavaScript:

  1. Divide the seconds by 60 to get the total minutes. The remainder will be the seconds in the output.
  2. Divide the total minutes by 60 to get the hours. The whole number in the result will be the hours, and the remainder will be the minutes in the output.
function toHoursAndMinutes(totalSeconds) < const totalMinutes = Math.floor(totalSeconds / 60); const seconds = totalSeconds % 60; const hours = Math.floor(totalMinutes / 60); const minutes = totalMinutes % 60; return < h: hours, m: minutes, s: seconds >; > // < h: 0, m: 1, s: 0 >console.log(toHoursAndMinutes(60)); // < h: 0, m: 16, s: 40 >console.log(toHoursAndMinutes(1000)); // < h: 1, m: 10, s: 50 >console.log(toHoursAndMinutes(4250)); 

We create a reusable function that takes a total number of seconds and returns an object containing the separate hours, minutes, and seconds values.

First, we divide the total seconds by 60 to get the number of total minutes.

console.log(60 / 60); // 1 console.log(1000 / 60); // 16.666666666666668 console.log(4250 / 60); // 70.83333333333333 

The division results in a decimal number, so we use the Math.floor() function to get just the whole number of the result.

Math.floor() returns the largest integer less than or equal to a specified number.

console.log(Math.floor(10.95)); // 10 console.log(Math.floor(10)); // 10 console.log(Math.floor(10.05)); // 10

After this, we use the modulo operator ( % ) to get the division’s remainder for the seconds in the result.

console.log(60 % 60); // 0 console.log(1000 % 60); // 40 console.log(4250 % 60); // 50 

Tip: Skip this step if the seconds should not be in the result.

We all know 60 seconds make a minute, and 60 minutes make an hour. After getting the total minutes, we do something similar to what we just did to the total seconds value: we divide the total minutes by 60 to get the hours and use the module operator to get the division’s remainder, which will be the minutes in the output.

After getting all the values, we return an object with h , m , and s properties containing the hours, minutes, and seconds respectively.

Convert seconds to HH:mm:ss

Instead of an object, you might want the result to be a time string in a format like HH:mm:ss , where each value is separated by a colon and has a minimum of two digits in the string. Here’s how we can produce such a time string.

function toTimeString(totalSeconds) < const totalMs = totalSeconds * 1000; const result = new Date(totalMs).toISOString().slice(11, 19); return result; >console.log(toTimeString(60)); // 00:01:00 console.log(toTimeString(1000)); // 00:16:40 console.log(toTimeString(4250)); // 01:10:50 

First, we convert the seconds to milliseconds to pass it to the Date() constructor and create a new Date object.

The Date toISOString() method returns a string representation of the date in the ISO 8601 format, i.e., YYYY-MM-DDTHH:mm:ss.sssZ

const totalMs = 60000; // 1970-01-01T00:01:00.000Z console.log(new Date(totalMs).toISOString());

You can see that toISOString() does the conversion for us. We just need a way to extract the HH:mm:ss from the ISO string.

The String slice() method returns the portion of a string between specified start and end indexes, passed as the first and second arguments respectively.

The HH:mm:ss starts at index 11 of the string and ends at index 18. So to extract it, the values we pass to slice() or substring() will be 11 and 19 .

Tip: 19 because slice() excludes the character at the end index from the resulting substring.

// 00:01:00 console.log('1970-01-01T00:01:00.000Z'.slice(11, 19)); 

To exclude the seconds from the result, we just need to reduce the end index by 3 to exclude the colon and the digits of the seconds.

// 00:01 console.log('1970-01-01T00:01:00.000Z'.slice(11, 16)); 

11 Amazing New JavaScript Features in ES13

This guide will bring you up to speed with all the latest features added in ECMAScript 13. These powerful new features will modernize your JavaScript with shorter and more expressive code.

11 Amazing New JavaScript Features in ES13

Ayibatari Ibaba is a software developer with years of experience building websites and apps. He has written extensively on a wide range of programming topics and has created dozens of apps and open-source libraries.

Источник

How to convert seconds to minutes and hours with vanilla JS

Working with time in JavaScript can be tricky. Today, I’m going to show you how to convert seconds in minutes and hours with vanilla JS.

Fair warning: we’re going to need to do some math.

Converting hours

Let’s say you had a timestamp in seconds that you wanted to display in HH:MM:SS format.

There are 60 seconds in a minute, and 60 minutes in an hour. We’ll divide our timestamp by 60 , and then by 60 again. That leaves us with 2.6283 repeating.

var timestamp = 9462; // 2.628333333 var hours = timestamp / 60 / 60; 

We want just hours, though. We can use Math.floor() to round down to the nearest whole number.

var timestamp = 9462; // 2 var hours = Math.floor(timestamp / 60 / 60); 

Converting minutes

There are 60 seconds in a minute. Let’s divide our timestamp by 60 , and use Math.floor() to round down to the nearest whole number. That leaves us with 157 , because it also includes all of the minutes that in our hours .

var timestamp = 9462; // 2 var hours = Math.floor(timestamp / 60 / 60); // 157 var minutes = Math.floor(timestamp / 60); 

We’ll multiply our hours by 60 to get its value in minutes, then subtract to it from our minutes to get the correct value.

var timestamp = 9462; // 2 var hours = Math.floor(timestamp / 60 / 60); // 37 var minutes = Math.floor(timestamp / 60) - (hours * 60); 

Calculating seconds

Finally, let’s calculate seconds.

For this one, we can use the remainder operator. It returns the amount leftover after dividing by a number.

We’ll use it to divide our timestamp by 60 (the number of seconds in a minute). The number we get back is the seconds after we remove all of the minutes.

var timestamp = 9462; // 2 var hours = Math.floor(timestamp / 60 / 60); // 37 var minutes = Math.floor(timestamp / 60) - (hours * 60); // 42 var seconds = timestamp % 60; 

Formatting time

Now that we have our hours , minutes , and seconds , we’re ready to format them into our HH:MM:SS format.

We can use simple string concatenation for this. JavaScript will type cooerce our integers into strings.

// 2:37:42 var formatted = hours + ':' + minutes + ':' + seconds; 

This might be good enough, but what if you wanted a leading 0 on the hours ? What if our minutes or seconds were single digit numbers?

We can convert our numbers to strings and use the padStart() method to enforce a minimum number of digits.

// 02:37:42 var formatted = hours.toString().padStart(2, '0') + ':' + minutes.toString().padStart(2, '0') + ':' + seconds.toString().padStart(2, '0'); 

Special thanks to Steve Griffith, whose video on this topic helped me work through one of the areas I was stuck on with this one.

Hate the complexity of modern front‑end web development? I send out a short email each weekday on how to build a simpler, more resilient web. Join over 14k others.

Made with ❤️ in Massachusetts. Unless otherwise noted, all code is free to use under the MIT License. I also very irregularly share non-coding thoughts.

Источник

Оцените статью