Update formatSeconds.md
This commit is contained in:
@ -1,26 +1,33 @@
|
||||
---
|
||||
title: formatSeconds
|
||||
tags: date,math,string
|
||||
tags: date,math,string,intermediate
|
||||
---
|
||||
|
||||
Returns the ISO format of the given number of seconds.
|
||||
|
||||
- Divide `s` with the appropriate values to obtain the appropriate values for "HH:mm:ss".
|
||||
- Use `Array.prototype.map()` to create the string for each value, and pads it to `2` digits.
|
||||
- Use `String.prototype.join(', ')` to combine the values into a string.
|
||||
- Divide `s` with the appropriate values to obtain the appropriate values for `hour`, `minute` and `second`.
|
||||
- Store the `sign` in a variable to prepend it to the result.
|
||||
- Use `Array.prototype.map()` in combination with `Array.prototype.floor()` and `String.prototype.padStart()` to stringify and format each segment.
|
||||
- Use `String.prototype.join(':')` to combine the values into a string.
|
||||
|
||||
```js
|
||||
const formatSeconds = s => {
|
||||
if (s < 0) s = 0;
|
||||
|
||||
return [s / 3600, s / 60 % 60, s % 60]
|
||||
.map(v => `${Math.floor(v).toString().padStart(2, '0')}`)
|
||||
.join(':');
|
||||
const [hour, minute, second, sign] =
|
||||
s > 0
|
||||
? [s / 3600, (s / 60) % 60, s % 60, '']
|
||||
: [-s / 3600, (-s / 60) % 60, -s % 60, '-'];
|
||||
|
||||
return (
|
||||
sign +
|
||||
[hour, minute, second]
|
||||
.map(v => `${Math.floor(v)}`.padStart(2, '0'))
|
||||
.join(':')
|
||||
);
|
||||
};
|
||||
```
|
||||
|
||||
```js
|
||||
formatSeconds(-200); // "00:00:00"
|
||||
formatSeconds(200); // "00:03:20"
|
||||
formatSeconds(99999); // "27:46:39"
|
||||
formatSeconds(200); // '00:03:20'
|
||||
formatSeconds(-200); // '-00:03:20'
|
||||
formatSeconds(99999); // '27:46:39'
|
||||
```
|
||||
|
||||
Reference in New Issue
Block a user