我想将持续时间转换为冒号分隔时间字符串的秒数(hh:mm:ss)
我在这里找到了一些有用的答案,但他们都谈到转换为x小时和x分钟格式。
那么有一个小代码片段可以用jQuery或原始JavaScript来完成吗?
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds;
}
您现在可以使用它:
alert("5678".toHHMMSS());
工作片段:
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second param
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours + ':' + minutes + ':' + seconds;
}
console.log("5678".toHHMMSS());
function formatTime(seconds) {
return [
parseInt(seconds / 60 / 60),
parseInt(seconds / 60 % 60),
parseInt(seconds % 60)
]
.join(":")
.replace(/\b(\d)\b/g, "0$1")
}
new Date().toString().split(" ")[4];
结果15:08:03
这很简单,
function toTimeString(seconds) {
return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}
s2t=function (t){
return parseInt(t/86400)+'d '+(new Date(t%86400*1000)).toUTCString().replace(/.*(\d{2}):(\d{2}):(\d{2}).*/, "$1h $2m $3s");
}
s2t(123456);
结果:
1d 10h 17m 36s
我喜欢Webjins的答案最多,所以我把它扩展到显示带有d后缀的日子,使显示有条件并且在普通秒上包含s后缀:
function sec2str(t){
var d = Math.floor(t/86400),
h = ('0'+Math.floor(t/3600) % 24).slice(-2),
m = ('0'+Math.floor(t/60)%60).slice(-2),
s = ('0' + t % 60).slice(-2);
return (d>0?d+'d ':'')+(h>0?h+':':'')+(m>0?m+':':'')+(t>60?s:s+'s');
}
返回“3d 16:32:12”或“16:32:12”或“32:12”或“12s”
我喜欢Powtac的答案,但我想在angular.js中使用它,所以我使用他的代码创建了一个过滤器。
.filter('HHMMSS', ['$filter', function ($filter) {
return function (input, decimals) {
var sec_num = parseInt(input, 10),
decimal = parseFloat(input) - sec_num,
hours = Math.floor(sec_num / 3600),
minutes = Math.floor((sec_num - (hours * 3600)) / 60),
seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+':'+minutes+':'+seconds;
if (decimals > 0) {
time += '.' + $filter('number')(decimal, decimals).substr(2);
}
return time;
};
}])
它在功能上是相同的,除了我在可选的小数字段中添加以显示小数秒。像使用任何其他过滤器一样使用它:
{{ elapsedTime | HHMMSS }}
显示:01:23:45
{{ elapsedTime | HHMMSS : 3 }}
显示:01:23:45.678
我认为性能明智是迄今为止最快的:
var t = 34236; // your seconds
var time = ('0'+Math.floor(t/3600) % 24).slice(-2)+':'+('0'+Math.floor(t/60)%60).slice(-2)+':'+('0' + t % 60).slice(-2)
//would output: 09:30:36
function toHHMMSS(seconds) {
var h, m, s, result='';
// HOURs
h = Math.floor(seconds/3600);
seconds -= h*3600;
if(h){
result = h<10 ? '0'+h+':' : h+':';
}
// MINUTEs
m = Math.floor(seconds/60);
seconds -= m*60;
result += m<10 ? '0'+m+':' : m+':';
// SECONDs
s=seconds%60;
result += s<10 ? '0'+s : s;
return result;
}
例子
toHHMMSS(111); "01:51" toHHMMSS(4444); "01:14:04" toHHMMSS(33); "00:33"
这是另一个版本,它也处理日子:
function FormatSecondsAsDurationString( seconds )
{
var s = "";
var days = Math.floor( ( seconds / 3600 ) / 24 );
if ( days >= 1 )
{
s += days.toString() + " day" + ( ( days == 1 ) ? "" : "s" ) + " + ";
seconds -= days * 24 * 3600;
}
var hours = Math.floor( seconds / 3600 );
s += GetPaddedIntString( hours.toString(), 2 ) + ":";
seconds -= hours * 3600;
var minutes = Math.floor( seconds / 60 );
s += GetPaddedIntString( minutes.toString(), 2 ) + ":";
seconds -= minutes * 60;
s += GetPaddedIntString( Math.floor( seconds ).toString(), 2 );
return s;
}
function GetPaddedIntString( n, numDigits )
{
var nPadded = n;
for ( ; nPadded.length < numDigits ; )
{
nPadded = "0" + nPadded;
}
return nPadded;
}
正则表达式可用于匹配从Date对象的toString()
方法返回的字符串中的时间子字符串,其格式如下:“Thu Jul 05 2012 02:45:12 GMT + 0100(GMT日光时间)”。请注意,此解决方案使用自纪元以来的时间:1970年1月1日午夜。此解决方案可以是单行,但将其拆分使其更容易理解。
function secondsToTime(seconds) {
const start = new Date(1970, 1, 1, 0, 0, 0, 0).getTime();
const end = new Date(1970, 1, 1, 0, 0, parseInt(seconds), 0).getTime();
const duration = end - start;
return new Date(duration).toString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}
您可以使用JS Date方法在没有任何外部JS库的情况下执行此操作,如下所示:
var date = new Date(null);
date.setSeconds(45); // specify value for SECONDS here
var timeString = date.toISOString().substr(11, 8);
console.log(timeString)
这就是我做到的。它似乎工作得相当好,而且非常紧凑。 (虽然它使用了很多三元运算符)
function formatTime(seconds) {
var hh = Math.floor(seconds / 3600),
mm = Math.floor(seconds / 60) % 60,
ss = Math.floor(seconds) % 60;
return (hh ? (hh < 10 ? "0" : "") + hh + ":" : "") + ((mm < 10) && hh ? "0" : "") + mm + ":" + (ss < 10 ? "0" : "") + ss
}
...以及格式化字符串......
String.prototype.toHHMMSS = function() {
formatTime(parseInt(this, 10))
};
您可以使用以下函数将时间(以秒为单位)转换为HH:MM:SS
格式:
var convertTime = function (input, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
return [
pad(Math.floor(input / 3600)),
pad(Math.floor(input % 3600 / 60)),
pad(Math.floor(input % 60)),
].join(typeof separator !== 'undefined' ? separator : ':' );
}
在不传递分隔符的情况下,它使用:
作为(默认)分隔符:
time = convertTime(13551.9941351); // --> OUTPUT = 03:45:51
如果你想使用-
作为分隔符,只需将它作为第二个参数传递:
time = convertTime(1126.5135155, '-'); // --> OUTPUT = 00-18-46
var convertTime = function (input, separator) {
var pad = function(input) {return input < 10 ? "0" + input : input;};
return [
pad(Math.floor(input / 3600)),
pad(Math.floor(input % 3600 / 60)),
pad(Math.floor(input % 60)),
].join(typeof separator !== 'undefined' ? separator : ':' );
}
document.body.innerHTML = '<pre>' + JSON.stringify({
5.3515555 : convertTime(5.3515555),
126.2344452 : convertTime(126.2344452, '-'),
1156.1535548 : convertTime(1156.1535548, '.'),
9178.1351559 : convertTime(9178.1351559, ':'),
13555.3515135 : convertTime(13555.3515135, ',')
}, null, '\t') + '</pre>';
另见this Fiddle。
块上的字符串有一种新方法:padStart
const str = '5';
str.padStart(2, '0'); // 05
这就是我做到的
function timeFromSecs(seconds)
{
return(
Math.floor(seconds/86400)+'d :'+
Math.floor(((seconds/86400)%1)*24)+'h : '+
Math.floor(((seconds/3600)%1)*60)+'m : '+
Math.round(((seconds/60)%1)*60)+'s');
}
timeFromSecs(22341938)将返回'258d 14h 5m 38s'
我个人更喜欢没有领先零的领先单位(天,小时,分钟)。但是秒应该总是以分钟为单位(0:13),这个演示文稿很容易被认为是“持续时间”,没有进一步的解释(标记为min,sec(s)等),可用于各种语言(国际化)。
// returns (-)d.h:mm:ss(.f)
// (-)h:mm:ss(.f)
// (-)m:ss(.f)
function formatSeconds (value, fracDigits) {
var isNegative = false;
if (isNaN(value)) {
return value;
} else if (value < 0) {
isNegative = true;
value = Math.abs(value);
}
var days = Math.floor(value / 86400);
value %= 86400;
var hours = Math.floor(value / 3600);
value %= 3600;
var minutes = Math.floor(value / 60);
var seconds = (value % 60).toFixed(fracDigits || 0);
if (seconds < 10) {
seconds = '0' + seconds;
}
var res = hours ? (hours + ':' + ('0' + minutes).slice(-2) + ':' + seconds) : (minutes + ':' + seconds);
if (days) {
res = days + '.' + res;
}
return (isNegative ? ('-' + res) : res);
}
//模仿服务器端(.net,C#)持续时间格式化如:
public static string Format(this TimeSpan interval)
{
string pattern;
if (interval.Days > 0) pattern = @"d\.h\:mm\:ss";
else if (interval.Hours > 0) pattern = @"h\:mm\:ss";
else pattern = @"m\:ss";
return string.Format("{0}", interval.ToString(pattern));
}
你可以使用Momement.js和moment-duration-format插件:
var seconds = 3820;
var duration = moment.duration(seconds, 'seconds');
var formatted = duration.format("hh:mm:ss");
console.log(formatted); // 01:03:40
<!-- Moment.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<!-- moment-duration-format plugin -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>
另见Fiddle
secToHHMM(number: number) {
debugger;
let hours = Math.floor(number / 3600);
let minutes = Math.floor((number - (hours * 3600)) / 60);
let seconds = number - (hours * 3600) - (minutes * 60);
let H, M, S;
if (hours < 10) H = ("0" + hours);
if (minutes < 10) M = ("0" + minutes);
if (seconds < 10) S = ("0" + seconds);
return (H || hours) + ':' + (M || minutes) + ':' + (S || seconds);
}
我赞成了artem的答案,但我是一张新的海报。我确实扩展了他的解决方案,但不是OP所要求的如下
t=(new Date()).toString().split(" ");
timestring = (t[2]+t[1]+' <b>'+t[4]+'</b> '+t[6][1]+t[7][0]+t[8][0]);
要得到
04Oct 16:31:28 PDT
这对我有用......
但是如果你只是从一个时间量开始,我使用两个函数;一个用于格式化和填充,一个用于计算:
function sec2hms(timect){
if(timect=== undefined||timect==0||timect === null){return ''};
//timect is seconds, NOT milliseconds
var se=timect % 60; //the remainder after div by 60
timect = Math.floor(timect/60);
var mi=timect % 60; //the remainder after div by 60
timect = Math.floor(timect/60);
var hr = timect % 24; //the remainder after div by 24
var dy = Math.floor(timect/24);
return padify (se, mi, hr, dy);
}
function padify (se, mi, hr, dy){
hr = hr<10?"0"+hr:hr;
mi = mi<10?"0"+mi:mi;
se = se<10?"0"+se:se;
dy = dy>0?dy+"d ":"";
return dy+hr+":"+mi+":"+se;
}
如果您知道您拥有的秒数,这将有效。它还使用本机Date()对象。
function formattime(numberofseconds){
var zero = '0', hours, minutes, seconds, time;
time = new Date(0, 0, 0, 0, 0, numberofseconds, 0);
hh = time.getHours();
mm = time.getMinutes();
ss = time.getSeconds()
// Pad zero values to 00
hh = (zero+hh).slice(-2);
mm = (zero+mm).slice(-2);
ss = (zero+ss).slice(-2);
time = hh + ':' + mm + ':' + ss;
return time;
}
toHHMMSS的非原型版本:
function toHHMMSS(seconds) {
var sec_num = parseInt(seconds);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
var time = hours+':'+minutes+':'+seconds;
return time;
}
要以hh:MM:ss
格式获取时间部分,可以使用此正则表达式:
(上面有人在同一篇文章中提到过,谢谢你。)
var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
console.log(myDate)
这是我对解决方案的看法。您可以在下面尝试我的代码段。
function secToHHMM(sec) {
var d = new Date();
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d = new Date(d.getTime() + sec*1000);
return d.toLocaleString('en-GB').split(' ')[1];
};
alert( 'One hour: ' + secToHHMM(60*60) ); // '01:00:00'
alert( 'One hour five minutes: ' + secToHHMM(60*60 + 5*60) ); // '01:05:00'
alert( 'One hour five minutes 23 seconds: ' + secToHHMM(60*60 + 5*60 + 23) ); // '01:05:23'
我推荐普通的javascript,使用Date对象:
var seconds = 9999;
// multiply by 1000 because Date() requires miliseconds
var date = new Date(seconds * 1000);
var hh = date.getUTCHours();
var mm = date.getUTCMinutes();
var ss = date.getSeconds();
// If you were building a timestamp instead of a duration, you would uncomment the following line to get 12-hour (not 24) time
// if (hh > 12) {hh = hh % 12;}
// These lines ensure you have two-digits
if (hh < 10) {hh = "0"+hh;}
if (mm < 10) {mm = "0"+mm;}
if (ss < 10) {ss = "0"+ss;}
// This formats your string to HH:MM:SS
var t = hh+":"+mm+":"+ss;
document.write(t);
(当然,创建的Date对象将具有与之关联的实际日期,但该数据是无关紧要的,因此出于这些目的,您不必担心它。)
谷歌搜索出现了this result:
function secondsToTime(secs)
{
secs = Math.round(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;
}
主题的变化。处理单个数字的秒数略有不同
seconds2time(0) -> "0s"
seconds2time(59) -> "59s"
seconds2time(60) -> "1:00"
seconds2time(1000) -> "16:40"
seconds2time(4000) -> "1:06:40"
function seconds2time (seconds) {
var hours = Math.floor(seconds / 3600);
var minutes = Math.floor((seconds - (hours * 3600)) / 60);
var seconds = seconds - (hours * 3600) - (minutes * 60);
var time = "";
if (hours != 0) {
time = hours+":";
}
if (minutes != 0 || time !== "") {
minutes = (minutes < 10 && time !== "") ? "0"+minutes : String(minutes);
time += minutes+":";
}
if (time === "") {
time = seconds+"s";
}
else {
time += (seconds < 10) ? "0"+seconds : String(seconds);
}
return time;
}
这是我的看法:
function formatTime(seconds) {
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = seconds % 60;
return [
h,
m > 9 ? m : (h ? '0' + m : m || '0'),
s > 9 ? s : '0' + s,
].filter(a => a).join(':');
}
预期成绩:
expect(formatTime(0)).toEqual('0:00');
expect(formatTime(1)).toEqual('0:01');
expect(formatTime(599)).toEqual('9:59');
expect(formatTime(600)).toEqual('10:00');
expect(formatTime(3600)).toEqual('1:00:00');
expect(formatTime(360009)).toEqual('100:00:09');
我喜欢第一个答案。有一些优化:
结果代码:
Number.prototype.toHHMMSS = function () {
var seconds = Math.floor(this),
hours = Math.floor(seconds / 3600);
seconds -= hours*3600;
var minutes = Math.floor(seconds / 60);
seconds -= minutes*60;
if (hours < 10) {hours = "0"+hours;}
if (minutes < 10) {minutes = "0"+minutes;}
if (seconds < 10) {seconds = "0"+seconds;}
return hours+':'+minutes+':'+seconds;
}
使用惊人的moment.js库:
function humanizeDuration(input, units ) {
// units is a string with possible values of y, M, w, d, h, m, s, ms
var duration = moment().startOf('day').add(units, input),
format = "";
if(duration.hour() > 0){ format += "H [hours] "; }
if(duration.minute() > 0){ format += "m [minutes] "; }
format += " s [seconds]";
return duration.format(format);
}
这允许您指定任何持续时间,包括小时,分钟,秒,铣削,并返回人类可读的版本。