JavaScript - Convert Days to Seconds
Tutorial to write a program to convert days to seconds using JavaScript.
In this tutorial, we will see how to convert days to seconds using JavaScript.
Before writing the program we should know that:
- There are 24 hours in one day
- 60 minutes in an hour, and
- 60 seconds in a minute
So, to convert days into seconds we have to multiply the days by 24 to get hours, 60 for the minutes and 60 for the seconds.
seconds = days * 24 * 60 * 60
Let's see it in code
const daysToSec = (days) => { return days * 24 * 60 * 60; } console.log(daysToSec(1)) //86400 console.log(daysToSec(20)) //1728000
Here, we have created a function daysToSec() , which take days as an argument and converts the days into seconds.
If you input your days in decimal form, it will return the seconds in decimal.
const daysToSec = (days) => { return days * 24 * 60 * 60; } console.log(daysToSec(1.534) + ' sec') //132537.6 sec
To solve this issue we have to use the Math.round() function of JavaScript.
The Math.round() function round a number to the nearest integer in JavaScript. For example,
Math.round(2.60); // 3 Math.round(4.50); // 5 Math.round(5.49); // 5
So we can modify the above daysToSec() function to round up the value.
const daysToSec = (days) => { return Math.round(days * 24 * 60 * 60); } console.log(daysToSec(1.534) + ' sec') //132538 sec
Conclusion: To convert days to seconds uisng JavaScript, we have to multiply the days by 24 hours, 60 minutes and 60 seconds i.e days*24*60*60.
Related Articles:
Convert seconds to minutes and seconds (mm:ss) using JavaScript
Related Posts
Convert seconds to minutes and seconds (mm:ss) using JavaScript
Find out how to convert seconds to minutes and second format mm:ss using toString() and padStart() in JavaScript.
Convert a Unix timestamp to time in JavaScript
Find out how to convert a unix timestamp to time format in JavaScript using toLocaleTimeString() method.
Fix error:0308010C:digital envelope routines::unsupported
Learn to solve the "Error: error:0308010C:digital envelope routines::unsupported" error in Node.js application (Vue, Angular or react) using the solutions in this article.
Press Shift + Enter for new Line in Textarea
Override default textarea behavior on Enter key press without Shift, prevent new lines, and take custom actions like submitting forms instead. Still allow Shift+Enter newlines.
