Is it possible to format seconds in a countdown style? For example, if I have var seconds = 3662
, how can I show: 1 hour 1 minute 2 seconds
.
I tried using formatDistanceStrict(3662)
but this is only printing the hour: 1 hour
.
Is there a built-in method to show the minutes and seconds too? I don't want to write 100 lines of code to get this working (like other examples from internet)
Since each minute has 60 seconds, converting seconds to minutes, divide the number of seconds by 60 to get the answer in seconds. Since each minute has 60 seconds, converting seconds to minutes, divide the number of seconds by 60 to get the answer in seconds.
PHP Code: <? php function convert_seconds($seconds) { $dt1 = new DateTime("@0"); $dt2 = new DateTime("@$seconds"); return $dt1->diff($dt2)->format('%a days, %h hours, %i minutes and %s seconds'); } echo convert_seconds(200000).
The time module of Python provides datetime. strftime() function to convert seconds into hours, minutes, and seconds. It takes time format and time. gmtime() function as arguments.
To convert milliseconds to hours, minutes, seconds:Divide the milliseconds by 1000 to get the seconds. Divide the seconds by 60 to get the minutes. Divide the minutes by 60 to get the hours. Add a leading zero if the values are less than 10 to format them consistently.
The simplest solution I could find, using the date-fns library, is this:
import { formatDuration, intervalToDuration } from 'date-fns';
function humanDuration(time: number) {
return formatDuration(intervalToDuration({start: 0, end: time * 1000}));
};
humanDuration(463441); // 5 days 8 hours 44 minutes 1 second
Is that, what you mean?
const seconds = 3662,
formatCounter = s => {
let _s = s
const units = {day: 864e2, hour: 3600, minute: 60, second: 1},
str = Object
.entries(units)
.reduce((r, [unit, multiplier]) => {
if(_s >= multiplier){
const count = _s/multiplier|0,
tail = count > 1 ? 's' : ''
r.push([count, unit+tail])
_s = _s%multiplier
}
return r
}, [])
return str.flat().join(' ')
}
console.log(formatCounter(seconds))
console.log(formatCounter(416920))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With