将刻度转换为时间格式(hh:mm:ss) [英] Convert ticks to time format (hh:mm:ss)

查看:77
本文介绍了将刻度转换为时间格式(hh:mm:ss)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从Web服务器获取视频时长值.我想以"hh:mm:ss"格式显示它.如何在JavaScript中做到这一点?

I am getting a video length value as ticks from web server. I want to display it in a "hh:mm:ss" format. How can I do this in JavaScript?

推荐答案

假设刻度线以秒为单位(如果不是,您可以先将它们转换为秒),则可以通过查找数字来获得所需的格式整个时间段中的整个分钟和几小时,然后剩下剩余的几秒钟. modulo 运算符很有用在这里,一个小时为3600秒,一分钟为60秒是一个事实:

Assuming that ticks are in seconds (you can convert them to seconds first if they aren't), you can get to the desired format by finding the number of whole minutes and hours in the time span, then taking the remaining seconds. The modulo operator is useful here, as is the fact that an hour is 3600 seconds, and a minute is 60 seconds:

function displayTime(ticksInSecs) {
    var ticks = ticksInSecs;
    var hh = Math.floor(ticks / 3600);
    var mm = Math.floor((ticks % 3600) / 60);
    var ss = ticks % 60;

    alert( pad(hh, 2) + ":" + pad(mm, 2) + ":" + pad(ss, 2) );
}

function pad(n, width) {
    var n = n + '';
    return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;
}

有关如何在JS中用前导零填充数字的信息,请参见此答案(上述方法是从该答案派生的).

See this answer for how to pad a number with leading zeros in JS (the method above is derived from this answer).

这篇关于将刻度转换为时间格式(hh:mm:ss)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆