如何在 javascript 中将秒转换为分和小时

我在变量 seconds中存储了秒数。例如,我想将1439秒转换为23分59秒。如果时间大于1小时(例如9432秒) ,则为2小时37分12秒。

我怎么才能做到呢?

我在想:

var sec, min, hour;


if(seconds<3600){
var a = Math.floor(seconds/60); //minutes
var b = seconds%60; //seconds


if (b!=1){
sec = "seconds";
}else{
sec = "second";
}


if(a!=1){
min = "minutes";
}else{
min = "minute";
}


$('span').text("You have played "+a+" "+min+" and "+b+" "+sec+".");
}else{
var a = Math.floor(seconds/3600); //hours
var x = seconds%3600;
var b = Math.floor(x/60); //minutes
var c = seconds%60; //seconds


if (c!=1){
sec = "seconds";
}else{
sec = "second";
}


if(b!=1){
min = "minutes";
}else{
min = "minute";
}


if(c!=1){
hour = "hours";
}else{
hour = "hour";
}


$('span').text("You have played "+a+" "+hour+", "+b+" "+min+" and "+c+" "+sec+".");
}

但是代码太多了,而且每秒都要计算,我怎么才能把它缩小呢?

149239 次浏览

我想你会发现 这个解决方案非常有帮助。

您可以修改显示格式,以满足您的需要,比如-

function secondsToHms(d) {
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);


var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
return hDisplay + mDisplay + sDisplay;
}

你可以试试这个,我以前成功地用过这个 您应该能够轻松地添加分钟和秒

function secondsToTime(secs)
{
var hours = Math.floor(secs / (60 * 60));


var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);


var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);


var obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
}

小提琴

可以将对象更改为

var obj = {
"h": hours + " hours",
"m": minutes + " minutes",
"s": seconds + " seconds"
};

我可能有点晚了,但是你可以用

Https://momentjs.com/

myVar = moment(myVar).format('HH:mm');

时刻提供大量的小时/日期等格式。

一个低脂肪的方法是:

function seconds_to_days_hours_mins_secs_str(seconds)
{ // day, h, m and s
var days     = Math.floor(seconds / (24*60*60));
seconds -= days    * (24*60*60);
var hours    = Math.floor(seconds / (60*60));
seconds -= hours   * (60*60);
var minutes  = Math.floor(seconds / (60));
seconds -= minutes * (60);
return ((0<days)?(days+" day, "):"")+hours+"h, "+minutes+"m and "+seconds+"s";
}

因此

> seconds_to_days_hours_mins_secs_str(9432+60*60*24)
'1 days, 2h, 37m and 12s'

这很容易理解,并根据需要进行扩展。

试试这个,把 SEC 转换成 H: M: S。

function convertTime(sec) {
var hours = Math.floor(sec/3600);
(hours >= 1) ? sec = sec - (hours*3600) : hours = '00';
var min = Math.floor(sec/60);
(min >= 1) ? sec = sec - (min*60) : min = '00';
(sec < 1) ? sec='00' : void 0;


(min.toString().length == 1) ? min = '0'+min : void 0;
(sec.toString().length == 1) ? sec = '0'+sec : void 0;


return hours+':'+min+':'+sec;
}

转换为 H: M

Number(moment.duration(Number(37320), 'seconds').hours()+'.'+moment.duration(Number(37320),'seconds').minutes())

我发现 Wilson Lee 和 Brian 的代码非常有用:

function formatTime(serverTimeinSeconds, elementId)
{ /* This converts seconds into days, hours, minutes and seconds timestring.
Requires JQuery if elementId argument is provided */
seconds = Math.floor(Number(serverTimeinSeconds));
days = Math.floor(seconds / (24*60*60));
seconds -= Math.floor(days    * (24*60*60));
hours    = Math.floor(seconds / (60*60));
seconds -= Math.floor(hours   * (60*60));
minutes  = Math.floor(seconds / (60));
seconds -= Math.floor(minutes * (60));


dDisplay = days > 0 ? days + (days == 1 ? ' day, ' : ' days, ') : '';
hDisplay = hours > 0 ? hours + (hours == 1 ? ' hour, ' : ' hours, ') : '';
mDisplay = minutes > 0 ? minutes + (minutes == 1 ? ' minute, ' : ' minutes, ') : '';
sDisplay = seconds > 0 ? seconds + (seconds == 1 ? ' second' : ' seconds') : '';


if (elementId != null) {
if (serverTimeinSeconds < 60) {
$(elementId).css('font-size', '15px');
$(elementId).html(sDisplay);
}
if (serverTimeinSeconds >= 60 && serverTimeinSeconds < 3600) {
$(elementId).css('font-size', '15px');
$(elementId).html(mDisplay + sDisplay);
}
if (serverTimeinSeconds >= 3600 && serverTimeinSeconds < 86400) {
$(elementId).css('font-size', '12px');
$(elementId).html(hDisplay + mDisplay + sDisplay);
}
if (serverTimeinSeconds >= 86400 && serverTimeinSeconds !== Infinity) {
$(elementId).css('font-size', '8px');
$(elementId).html(dDisplay + hDisplay + mDisplay + sDisplay);
}
}
return dDisplay + hDisplay + mDisplay + sDisplay;
}

@ pkerckhove 已经提到 moment是一个很好的处理日期和时间的库,你也可以使用 moment直接将秒数格式化为 OP 所需的格式,比如:

import moment from 'moment'


const myVar = 1439
console.log(
moment.unix(myVar).utc().format('H [hours,] m [minutes and] s [seconds]')
)

将导致: 0 hours, 23 minutes and 59 seconds和,

import moment from 'moment'


const myVar = 9432
console.log(
moment.unix(myVar).utc().format('H [hours,] m [minutes and] s [seconds]')
)

将导致: 2 hours, 37 minutes and 12 seconds

试试这个 D

secondsToHms(d) {
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);


var hDisplay = h > 0 ? h + (h == 1 ? "" : "") : "";
var mDisplay = m > 0 ? m + (m == 1 ? "" : "") : "";
var sDisplay = s > 0 ? s + (s == 1 ? "" : "") : "";
if (hDisplay != "") {
return (hDisplay.length > 1 ? hDisplay : '0' + hDisplay) + ":" + (mDisplay.length > 1 ? mDisplay : '0' + mDisplay) + ":" + (sDisplay.length > 1 ? sDisplay : '0' + sDisplay);
}
else if (mDisplay != "") {
return (mDisplay.length > 1 ? mDisplay : '0' + mDisplay) + ":" + (sDisplay.length > 1 ? sDisplay : '0' + sDisplay);
}
else if (sDisplay != "") {
return "00:" + (sDisplay.length > 1 ? sDisplay : '0' + sDisplay);
}
return "00:00"
}

一种方法是:

const formatDuration = totalSeconds => {
const hours = Math.floor(totalSeconds / 3600)
const minutes = Math.floor((totalSeconds % 3600) / 60)
const seconds = totalSeconds - hours * 3600 - minutes * 60


return [`${hours}h`, `${minutes}m`, `${seconds}s`]
.filter(item => item[0] !== '0')
.join(' ')
}

内置的 JavaScript Date 对象可以简化所需的代码

 toTime(seconds) {
var date = new Date(null);
date.setSeconds(seconds);
return date.toISOString().substr(11, 8);
}
 const formatter = (seconds = 0) => {
const d = Number(secondsAmount);
const h = Math.floor(d / 3600);
const m = Math.floor((d % 3600) / 60);
const s = Math.floor((d % 3600) % 60);
const hDisplay = h > 0 ? `${h.toString().length > 1 ? `${h}` : `${0}${h}`}` : '00';
const mDisplay = m > 0 ? `${m.toString().length > 1 ? `${m}` : `${0}${m}`}` : '00';
const sDisplay = s > 0 ? `${s.toString().length > 1 ? `${s}` : `${0}${s}`}` : '00';
return `${hDisplay}:${mDisplay}:${sDisplay}`;
};

将返回此格式的人类可读格式 早上好

Please install moment js after that import it,


import moment from 'moment'


let dateForm = (arg) => {
return moment.unix(arg).utc().format('H [hours,] m [minutes and] s [seconds]');
}


console.log(dateForm(11));
// 0 hours, 0 minutes and 11 seconds

Log (dateForm (16060)) ; 1小时0分0秒

使用流行的 约会

import { format, setSeconds, startOfDay } from 'date-fns'


export const hourMinSec = (secs: number, showHour = false): string => {


const tmpDate: Date = startOfDay(new Date())
const date: Date = setSeconds(tmpDate, secs)
const hour: number = date.getHours()
const hasHour: boolean = !!hour


if (hasHour && !showHour) console.warn('hourMinSec is hiding a non zero hour')


const strFormat: string = showHour ? 'H:mm:ss' : 'm:ss'
return format(date, strFormat)
}

使用功能性更强的方法或相同的代码(在混合中添加 loash 流)

import { setSeconds, startOfDay } from 'date-fns/fp'
import { format } from 'date-fns'
import { flow } from 'lodash-es'


export const hourMinSec = (secs: number, showHour = false): string => {
const date: Date = flow(startOfDay, setSeconds(secs))(new Date())
const hour: number = date.getHours()
const hasHour: boolean = !!hour


if (hasHour && !showHour) console.warn('hourMinSec is hiding a non zero hour')


const strFormat: string = showHour ? 'H:mm:ss' : 'm:ss'
return format(date, strFormat)
}

用法:

hourMinSec(100)         //    1:40
hourMinSec(3700)        //    1:40 // will warn in logs that a non zero hour is hidden
hourMinSec(100, true)   // 0:01:40
hourMinSec(3700, true)  // 1:01:40

这满足了我的需要,但是您可以通过将 showHour = false参数更改为 strFormat = 'm:ss'参数以支持更灵活的格式化来改变这一点。

const minutes = Math.floor(duration / 60);
const seconds = Math.floor(duration - minutes * 60);


const time = `${minutes < 10 ? `0${minutes}` : minutes}
:${seconds < 10 ? `0${seconds}` : seconds}`; // result: 02:23

基于 R4nc1d 的回答:

function secondsToTime(secs){
var h = Math.floor(secs / (60 * 60));


var divisor_for_minutes = secs % (60 * 60);
var m = Math.floor(divisor_for_minutes / 60);


var divisor_for_seconds = divisor_for_minutes % 60;
var s = Math.ceil(divisor_for_seconds);


return `${h?`${h}:`:""}${m?`${m}:${s}`:`${s}s`}`
}

这将返回一个人类可读的答案,看起来像这样。我用这个来显示音轨的长度

time = secondsToTime(5)
console.log(time)         // 5s
time = secondsToTime(50)
console.log(time)         // 50s
time = secondsToTime(500)
console.log(time)         // 8:20
time = secondsToTime(5000)
console.log(time)         // 1:23:20

这种方法也适用于时间为负数的情况:

function CalculateTime(sec){


if(sec >= 0){
var h = Math.floor(sec / 3600);
var m = Math.floor(sec % 3600 / 60);
var s = Math.floor(sec % 3600 % 60);
}
else{
var h = Math.ceil(sec / 3600);
var m = Math.ceil(sec % 3600 / 60);
var s = Math.ceil(sec % 3600 % 60);
}


var hDisplay = h !== 0 ? h + (h == 1 ? " hour, " : " hours") + (m != 0 || s > 0 ? ", ":"") : "";
var mDisplay = m !== 0 ? m + (m == 1 ? " minute, " : " minutes")  + (s != 0 ? " ":""): "";
var sDisplay = s !== 0 ? s + (s == 1 ? " second" : " seconds") : "";
return hDisplay + mDisplay + sDisplay;
}

为了获得时间格式为“00:00:00”的结果,我对其进行了一些更改。

function secondsToHms(seconds) {


let d = Number(seconds);


if(d <= 0){
return '00:00:00'
}else{
let h = Math.floor(d / 3600);
let m = Math.floor(d % 3600 / 60);
let s = Math.floor(d % 3600 % 60);


let hDisplay = h <= 9 ? '0'+ h+':' : h+ ":";
let mDisplay = m <= 9 ? '0'+ m+':' : m+ ":";
let sDisplay = s <= 9 ? '0'+ s : s;




return hDisplay + mDisplay + sDisplay;


}}

使用倒计时钩

// useCountDown.js


import { useEffect, useState } from "react"


const useCountDown = (minutes) => {
const [seconds, setSeconds] = useState(minutes * 60)


useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds - 1)
}, 1000)


return () => clearInterval(interval)
}, [seconds])


return getReturnValues2(seconds)
}


const getReturnValues2 = (countDown) => {


const minutes = Math.floor(countDown / 60)
const seconds = countDown % 60


return `${padTo2Digits(minutes)}:${padTo2Digits(seconds)}`
}


function padTo2Digits(num) {
return num.toString().padStart(2, "0")
}


export default useCountDown


怎么用?

//React Component


import useCountDown from '../hooks/useCountDown'


function App() {
const countDown = useCountDown(5) // 5 Minutes
return (
<h1> {countDown} </h1>   // MM:SS
)
}

您可以根据需要进行调整。