Convert Days to Seconds using JavaScript

avatar

Borislav Hadzhiev

Fri Jan 28 20222 min read

banner

Photo by Meiying Ng

Convert days to seconds using JavaScript #

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.

index.js
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.

To convert the days to seconds, we have to multiply by 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.

index.js
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.

index.js
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.

index.js
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.

If the number is positive and its fractional part is greater than or equal to 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.