Convert Days to Milliseconds in JavaScript

avatar

Borislav Hadzhiev

Fri Jan 28 20222 min read

banner

Photo by Meiying Ng

Convert days to milliseconds in JavaScript #

To convert days to milliseconds, multiply the days by 24 for the hours, 60 for the minutes, 60 for the seconds and 1000 for the milliseconds, e.g. days * 24 * 60 * 60 * 1000.

index.js
function daysToMilliseconds(days) { // 👇️ hour min sec ms return days * 24 * 60 * 60 * 1000; } console.log(daysToMilliseconds(1)); // 👉️ 86400000 console.log(daysToMilliseconds(2)); // 👉️ 17280000 console.log(daysToMilliseconds(5)); // 👉️ 432000000

We created a reusable function that takes the number of days as parameter and converts the days to milliseconds.

To convert the days to milliseconds, we have to multiply by 24 to convert to hours, 60 to convert to minutes, 60 to convert to seconds and 1000 to convert to milliseconds.

If your application uses fractional units for the days, you might get a decimal number after the conversion.

index.js
function daysToMilliseconds(days) { // 👇️ hour min sec ms return days * 24 * 60 * 60 * 1000; } console.log(daysToMilliseconds(5.5612)); // 👉️ 442367999.99999

You can use the Math.round() function to round the number to the nearest integer.

index.js
function daysToMilliseconds(days) { // 👇️ hour min sec ms return Math.round(days * 24 * 60 * 60 * 1000); } console.log(daysToMilliseconds(5.5612)); // 👉️ 442368000

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(3.49)); // 👉️ 3 console.log(Math.round(3.5)); // 👉️ 4

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.