使用格式hh:mm:ss的JavaScript秒到时间字符串

时间:2011-06-10 23:23:16

标签: javascript date time date-format time-format

我想将持续时间转换为冒号分隔时间字符串的秒数(hh:mm:ss)

我在这里找到了一些有用的答案,但他们都谈到转换为x小时和x分钟格式。

那么是否有一个小小的片段在jQuery中执行此操作或仅使用原始JavaScript?

45 个答案:

答案 0 :(得分:517)

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());

答案 1 :(得分:128)

你可以设法在没有任何外部JS库的情况下使用JS Date方法执行此操作,如下所示:

&#13;
&#13;
var date = new Date(null);
date.setSeconds(45); // specify value for SECONDS here
var timeString = date.toISOString().substr(11, 8);
console.log(timeString)
&#13;
&#13;
&#13;

答案 2 :(得分:76)

要以hh:MM:ss格式获取时间部分,您可以使用此正则表达式:

(上面有人在同一篇文章中提到过,谢谢你。)

    var myDate = new Date().toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
    console.log(myDate)

答案 3 :(得分:48)

我推荐普通的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对象将具有与之关联的实际日期,但该数据是无关紧要的,因此出于这些目的,您不必担心它。)

答案 4 :(得分:36)

Google搜索出现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;
}

答案 5 :(得分:28)

主题的变化。处理单个数字的秒数略有不同

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;
}

答案 6 :(得分:15)

这是我的看法:

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');

答案 7 :(得分:13)

我喜欢第一个答案。 有一些优化:

  • 源数据是一个数字。不需要额外的计算。

  • 多余的计算

结果代码:

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;
}

答案 8 :(得分:12)

使用了惊人的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);
}

这允许您指定任何持续时间,包括小时,分钟,秒,磨,并返回人类可读的版本。

答案 9 :(得分:10)

function formatTime(seconds) {
    return [
        parseInt(seconds / 60 / 60),
        parseInt(seconds / 60 % 60),
        parseInt(seconds % 60)
    ]
        .join(":")
        .replace(/\b(\d)\b/g, "0$1")
}

答案 10 :(得分:10)

new Date().toString().split(" ")[4];

结果15:08:03

答案 11 :(得分:9)

这很简单,

function toTimeString(seconds) {
  return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}

答案 12 :(得分:8)

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

答案 13 :(得分:6)

我喜欢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”

答案 14 :(得分:6)

我喜欢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

答案 15 :(得分:5)

最简单的方法。

new Date(sec * 1000).toISOString().substr(11, 8)

答案 16 :(得分:4)

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"

答案 17 :(得分:3)

我认为表现明智这是迄今为止最快的:

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

答案 18 :(得分:3)

正则表达式可用于匹配从Date对象的toString()方法返回的字符串中的时间子字符串,其格式如下:“Thu Jul 05 2012 02:45:12 GMT + 0100 (格林威治标准时间日光时间)“。请注意,此解决方案使用自纪元以来的时间: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");
}

答案 19 :(得分:3)

这是另一个版本,它也处理了几天:

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;
}

答案 20 :(得分:2)

我是这样做的。它似乎工作得相当好,而且非常紧凑。 (虽然它使用了很多三元运算符)

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))
};

答案 21 :(得分:2)

块上有字符串的新方法: padStart

const str = '5';
str.padStart(2, '0'); // 05

以下是一个示例用例:YouTube durations in 4 lines of JavaScript

答案 22 :(得分:2)

您可以使用以下函数将时间(以秒为单位)转换为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

答案 23 :(得分:1)

我就这样做了

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'

答案 24 :(得分:1)

我个人更喜欢没有前导零的领先单位(天,小时,分钟)。但是秒应该总是以分钟为单位(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));
    }

答案 25 :(得分:1)

最普遍的答案是

function hms(seconds) {
  return [3600, 60]
    .reduceRight(
      (p, b) => r => [Math.floor(r / b)].concat(p(r % b)),
      r => [r]
    )(seconds)
    .map(a => a.toString().padStart(2, '0'))
    .join(':');
}

一些示例输出:

> hms(0)
< "00:00:00"

> hms(5)
< "00:00:05"

> hms(60)
< "00:01:00"

> hms(3785)
< "01:03:05"

> hms(37850)
< "10:30:50"

> hms(378500)
< "105:08:20"

请参阅 https://stackoverflow.com/a/66504936/1310733

处的说明

答案 26 :(得分:1)

这是我最近为MM:SS写的。这个问题并不精确,但这是一种不同的单行格式。

const time = 60 * 2 + 35; // 2 minutes, 35 seconds
const str = (~~(time / 60) + "").padStart(2, '0') + ":" + (~~((time / 60) % 1 * 60) + "").padStart(2, '0');

str // 02:35

编辑:添加的目的是为了多样化,但是最好的解决方案是下面的https://stackoverflow.com/a/25279399/639679

答案 27 :(得分:1)

您可以将Momement.jsmoment-duration-format插件一起使用:

&#13;
&#13;
var seconds = 3820;
var duration = moment.duration(seconds, 'seconds');
var formatted = duration.format("hh:mm:ss");
console.log(formatted); // 01:03:40
&#13;
<!-- 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>
&#13;
&#13;
&#13;

另见Fiddle

答案 28 :(得分:1)

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);
}

答案 29 :(得分:0)

这是使用 Date.prototype.toLocaleTimeString() 的示例。我选择 GB 作为语言,因为美国在最初的一小时显示 24 而不是 00。此外,我选择 Etc/UTC 作为时区,因为 UTClist of tz database time zones 中是它的别名。

const formatTime = (seconds) =>
  new Date(seconds * 1000).toLocaleTimeString('en-GB', {
    timeZone:'Etc/UTC',
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });

console.log(formatTime(75)); // 00:01:15
.as-console-wrapper { top: 0; max-height: 100% !important; }

这是相同的示例,但使用 Intl.DateTimeFormat。此变体可让您实例化可重用的格式化程序对象,从而提高性能。

const dateFormatter = new Intl.DateTimeFormat('en-GB', {
  timeZone:'Etc/UTC',
  hour12: false,
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit'
});

const formatTime = (seconds) => dateFormatter.format(new Date(seconds * 1000));

console.log(formatTime(75)); // 00:01:15
.as-console-wrapper { top: 0; max-height: 100% !important; }

答案 30 :(得分:0)

如果你知道你拥有的秒数,这将有效。它还使用本机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; 
}

答案 31 :(得分:0)

这是一个相当简单的解决方案,可以四舍五入到最接近的秒!

var returnElapsedTime = function(epoch) {
  //We are assuming that the epoch is in seconds
  var hours = epoch / 3600,
      minutes = (hours % 1) * 60,
      seconds = (minutes % 1) * 60;
  return Math.floor(hours) + ":" + Math.floor(minutes) + ":" + Math.round(seconds);
}

答案 32 :(得分:0)

我看到每个人都在发表自己的看法,尽管事实上,几乎没有什么最重要的答案已经包含了针对特定用例进行量身定制的所有必要信息。

由于我也想变得时髦-这是我不必要且有点麻烦的解决方案,即:

a)可读(希望如此)
b)易于定制
c)不打印任何零

鼓卷

function durationToDDHHMMSSMS(durms) {
    if (!durms) return "??";

    var HHMMSSMS = new Date(durms).toISOString().substr(11, 12);
    if (!HHMMSSMS) return "??";

    var HHMMSS = HHMMSSMS.split(".")[0];
    if (!HHMMSS) return "??";

    var MS = parseInt(HHMMSSMS.split(".")[1],10);
    var split = HHMMSS.split(":");
    var SS = parseInt(split[2],10);
    var MM = parseInt(split[1],10);
    var HH = parseInt(split[0],10); 
    var DD = Math.floor(durms/(1000*60*60*24));

    var string = "";
    if (DD) string += ` ${DD}d`;
    if (HH) string += ` ${HH}h`;
    if (MM) string += ` ${MM}m`;
    if (SS) string += ` ${SS}s`;
    if (MS) string += ` ${MS}ms`;

    return string;
},

请注意,此代码使用ES6模板字符串,我相信,像您这样的聪明人,在需要时用常规字符串替换它们不会有任何困难。

答案 33 :(得分:0)

这是2019年更新的单线:

//your date
var someDate = new Date("Wed Jun 26 2019 09:38:02 GMT+0100") 

var result = `${String(someDate.getHours()).padStart(2,"0")}:${String(someDate.getMinutes()).padStart(2,"0")}:${String(someDate.getSeconds()).padStart(2,"0")}`

//result will be "09:38:02"

答案 34 :(得分:0)

这是它的es6版本:

export const parseTime = (time) => { // send time in seconds
// eslint-disable-next-line 
let hours = parseInt(time / 60 / 60), mins = Math.abs(parseInt(time / 60) - (hours * 60)), seconds = Math.round(time % 60);
return isNaN(hours) || isNaN(mins) || isNaN(seconds) ? `00:00:00` : `${hours > 9 ? Math.max(hours, 0) : '0' + Math.max(hours, 0)}:${mins > 9 ? Math.max(mins, 0) : '0' + Math.max(0, mins)}:${seconds > 9 ? Math.max(0, seconds) : '0' + Math.max(0, seconds)}`;}

答案 35 :(得分:0)

/**
 * Formats seconds (number) to H:i:s format.
 * 00:12:00
 *
 * When "short" option is set to true, will return:
 * 0:50
 * 2:00
 * 12:00
 * 1:00:24
 * 10:00:00
 */
export default function formatTimeHIS (seconds, { short = false } = {}) {
  const pad = num => num < 10 ? `0${num}` : num

  const H = pad(Math.floor(seconds / 3600))
  const i = pad(Math.floor(seconds % 3600 / 60))
  const s = pad(seconds % 60)

  if (short) {
    let result = ''
    if (H > 0) result += `${+H}:`
    result += `${H > 0 ? i : +i}:${s}`
    return result
  } else {
    return `${H}:${i}:${s}`
  }
}

答案 36 :(得分:0)

&#13;
&#13;
l
&#13;
&#13;
&#13;

其中locale参数(&#34; en&#34;,&#34; de&#34;等)是可选的

答案 37 :(得分:0)

持续时间毫秒,简单方法:

// To have leading zero digits in strings.
function pad(num, size) {
    var s = num + "";
    while (s.length < size) s = "0" + s;
    return s;
}

// ms to time/duration
msToDuration = function(ms){
    var seconds = ms / 1000;
    var hh = Math.floor(seconds / 3600),
    mm = Math.floor(seconds / 60) % 60,
    ss = Math.floor(seconds) % 60,
    mss = ms % 1000;
    return pad(hh,2)+':'+pad(mm,2)+':'+pad(ss,2)+'.'+pad(mss,3);
}

它会将327577转换为00:05:27.577

<强>更新

针对不同场景的另一种方式:

toHHMMSS = function (n) {
    var sep = ':',
        n = parseFloat(n),
        sss = parseInt((n % 1)*1000),
        hh = parseInt(n / 3600);
    n %= 3600;
    var mm = parseInt(n / 60),
        ss = parseInt(n % 60);
    return pad(hh,2)+sep+pad(mm,2)+sep+pad(ss,2)+'.'+pad(sss,3);
    function pad(num, size) {
        var str = num + "";
        while (str.length < size) str = "0" + str;
        return str;
    }
}

toHHMMSS(6315.077) // Return 01:45:15.077

答案 38 :(得分:0)

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);

    if(hours >= 12)
    {
     var m= 'pm' ;
     }
     else
     {
         var m='am'
     }
     if(hours-12 >0)
     {
            var hrs = hours-12;
     }
     else if(hours-12 <0)
     {
            var hrs = hours;
     }
    var obj = {
        "h": hrs,
        "m": minutes,
        "s": seconds,
        "a":m
    };


    return obj;
}
var d = new Date();
var n = d.getHours();
var hms = d.getHours()+':'+d.getMinutes()+':'+d.getSeconds();   // your input string
var a = hms.split(':'); // split it at the colons

// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); 




console.log(seconds);
console.log(secondsToTime(seconds))

https://jsfiddle.net/jithinksoft/9x6z4sdt/

答案 39 :(得分:0)

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;
    }   

答案 40 :(得分:0)

我赞成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;
}

答案 41 :(得分:0)

            //secondsToTime();
            var t = wachttijd_sec; // your seconds
            var hour = Math.floor(t/3600);
            if(hour < 10){
                hour = '0'+hour;
            }
            var time = hour+':'+('0'+Math.floor(t/60)%60).slice(-2)+':'+('0' + t % 60).slice(-2);
            //would output: 00:00:00 > +100:00:00
即使超过24小时,

仍会保持对抗

答案 42 :(得分:0)

如果你正在处理视频长度,这个版本的接受答案会让它更漂亮,例如:

1:37:40(1小时/ 37分钟/ 40秒)

1:00(1分钟)

2:20(2分20秒)

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);

  var hourSeparator = ':';
  var minuteSeparator = ':';

  if(hours == 0){hours = '';hourSeparator = '';}
  if (minutes < 10 && hours != 0) {minutes = "0"+minutes;}
  if (seconds < 10) {seconds = "0"+seconds;}
  var time = hours+hourSeparator+minutes+minuteSeparator+seconds;
  return time;
}

答案 43 :(得分:0)

这是我对解决方案的看法。您可以尝试下面的代码段。

&#13;
&#13;
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'
&#13;
&#13;
&#13;

答案 44 :(得分:-2)

我不喜欢在JavaScript中向标准数据类型添加属性,因此我建议这样:

/**
 * Format a duration in seconds to a human readable format using the notion
 * "h+:mm:ss", e.g. "4:40:78". Negative durations are preceeded by "-".
 *
 * @param t Duration in seconds
 * @return The formatted duration string
 */
var readableDuration = (function() {

    // Each unit is an object with a suffix s and divisor d
    var units = [
        {s: '', d: 1}, // Seconds
        {s: ':', d: 60}, // Minutes
        {s: ':', d: 60}, // Hours
    ];

    // Closure function
    return function(t) {
        t = parseInt(t); // In order to use modulus
        var trunc, n = Math.abs(t), i, out = []; // out: list of strings to concat
        for (i = 0; i < units.length; i++) {
            n = Math.floor(n / units[i].d); // Total number of this unit
            // Truncate e.g. 26h to 2h using modulus with next unit divisor
            if (i+1 < units.length) // Tweak substr with two digits
                trunc = ('00'+ n % units[i+1].d).substr(-2, 2); // …if not final unit
            else
                trunc = n;
            out.unshift(''+ trunc + units[i].s); // Output
        }
        (t < 0) ? out.unshift('-') : null; // Handle negative durations
        return out.join('');
    };
})();

用法:

var str = readableDuration(3808); // "1:03:28"

我还创建了更多generally usable version。主要区别在于它接受毫秒(这是JS中的标准时间单位),输出格式使用空格。