以秒为单位格式化时间间隔为 X 小时 Y 分钟 Z 秒
Format time interval in seconds as X hour(s) Y minute(s) Z second(s)
是否可以将秒设置为倒计时样式?比如我有var seconds = 3662
,我怎么显示:1 hour 1 minute 2 seconds
.
我尝试使用 formatDistanceStrict(3662)
但这只打印小时:1 hour
.
是否也有显示分钟和秒的内置方法?我不想写 100 行代码来让它工作(就像互联网上的其他例子一样)
你在找这个吗
这里我把秒换成了分和小时
并返回字符串。
function format(time) {
// Hours, minutes and seconds
var hrs = ~~(time / 3600);
var mins = ~~((time % 3600) / 60);
var secs = ~~time % 60;
// Output like "1:01" or "4:03:59" or "123:03:59"
var ret = "";
if (hrs > 0) {
ret += "" + hrs + " hour " + (mins < 10 ? "0" : "");
}
ret += "" + mins + " minutes " + (secs < 10 ? "0" : "");
ret += "" + secs + " seconds";
return ret;
}
console.log(format(3662));
你是这个意思吗?
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))
简单如:
const time = new Date(0,0,0)
time.setSeconds(3662)
console.log(time.getHours(),
time.getMinutes(),
time.getSeconds())
使用 date-fns 库,我能找到的最简单的解决方案是:
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
是否可以将秒设置为倒计时样式?比如我有var seconds = 3662
,我怎么显示:1 hour 1 minute 2 seconds
.
我尝试使用 formatDistanceStrict(3662)
但这只打印小时:1 hour
.
是否也有显示分钟和秒的内置方法?我不想写 100 行代码来让它工作(就像互联网上的其他例子一样)
你在找这个吗
这里我把秒换成了分和小时
并返回字符串。
function format(time) {
// Hours, minutes and seconds
var hrs = ~~(time / 3600);
var mins = ~~((time % 3600) / 60);
var secs = ~~time % 60;
// Output like "1:01" or "4:03:59" or "123:03:59"
var ret = "";
if (hrs > 0) {
ret += "" + hrs + " hour " + (mins < 10 ? "0" : "");
}
ret += "" + mins + " minutes " + (secs < 10 ? "0" : "");
ret += "" + secs + " seconds";
return ret;
}
console.log(format(3662));
你是这个意思吗?
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))
简单如:
const time = new Date(0,0,0)
time.setSeconds(3662)
console.log(time.getHours(),
time.getMinutes(),
time.getSeconds())
使用 date-fns 库,我能找到的最简单的解决方案是:
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