Borislav Hadzhiev
Fri Jan 28 2022·2 min read
Photo by Meiying Ng
To convert days to seconds, multiply the days by 24
for the hours, 60
for
the minutes and 60
for the seconds, e.g. days * 24 * 60 * 60
. The result
from the multiplication will represent the seconds equivalent for the number of
days.
function daysToSeconds(days) { // 👇️ hour min sec return days * 24 * 60 * 60; } console.log(daysToSeconds(1)); // 👉️ 86400 console.log(daysToSeconds(2)); // 👉️ 172800 console.log(daysToSeconds(5)); // 👉️ 432000
We created a reusable function that takes the number of days as parameter and converts the days to seconds.
24
to convert to hours, 60
to convert to minutes and 60
to convert to seconds.If your application uses fractional units for the days, you might get a decimal number after the conversion.
function daysToSeconds(days) { // 👇️ hour min sec return days * 24 * 60 * 60; } console.log(daysToSeconds(3.5612)); // 👉️ 307687.68
You can use the Math.round()
function to round the number to the nearest
integer.
function daysToSeconds(days) { // 👇️ hour min sec return Math.round(days * 24 * 60 * 60); } console.log(daysToSeconds(3.5612)); // 👉️ 307688
We passed the value to the Math.round function to round to the nearest integer and make sure we don't get a decimal after the conversion.
Here are some examples of how the Math.round
function works.
console.log(Math.round(7.49)); // 👉️ 7 console.log(Math.round(7.5)); // 👉️ 8
The function rounds the number up or down to the nearest integer.
0.5
, it gets rounded to the next higher absolute value.If the number is positive and its fractional portion is less than 0.5
, it gets
rounded to the lower absolute value.