Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2008/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用JavaScript将秒转换为HH-MM-SS?_Javascript_Date_Time_Date Format_Time Format - Fatal编程技术网

使用JavaScript将秒转换为HH-MM-SS?

使用JavaScript将秒转换为HH-MM-SS?,javascript,date,time,date-format,time-format,Javascript,Date,Time,Date Format,Time Format,如何使用JavaScript将秒转换为HH-MM-SS字符串?更新(2020): 请使用@Frank的单线解决方案: new Date(SECONDS * 1000).toISOString().substr(11, 8) 这是迄今为止最好的解决办法 旧答案: 使用该库。我认为标准日期对象的任何内置功能都不会比自己计算更方便 hours = Math.floor(totalSeconds / 3600); totalSeconds %= 3600; minutes = Math.floor(

如何使用JavaScript将秒转换为
HH-MM-SS
字符串?

更新(2020):

请使用@Frank的单线解决方案:

new Date(SECONDS * 1000).toISOString().substr(11, 8)
这是迄今为止最好的解决办法


旧答案:


使用该库。

我认为标准日期对象的任何内置功能都不会比自己计算更方便

hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
minutes = Math.floor(totalSeconds / 60);
seconds = totalSeconds % 60;
例如:

secondsToTime(101596) // outputs '28:13:16' as opposed to '04:13:16'
让totalSeconds=28565;
让小时数=数学楼层(总秒数/3600);
总秒数%=3600;
分钟=数学地板(总秒数/60);
设秒数=总秒数%60;
控制台日志(“小时:+小时);
console.log(“分钟数:+分钟数”);
console.log(“秒:+秒);
//如果要使用前导零的字符串:
分钟=字符串(分钟).padStart(2,“0”);
小时=字符串(小时).padStart(2,“0”);
秒=字符串(秒).padStart(2,“0”);
console.log(小时+“:“+分钟+”:“+秒)这样做的诀窍是:

function secondstotime(secs)
{
    var t = new Date(1970,0,1);
    t.setSeconds(secs);
    var s = t.toTimeString().substr(0,8);
    if(secs > 86399)
        s = Math.floor((t - Date.parse("1/1/70")) / 3600000) + s.substr(2);
    return s;
}
(来源于)

var time1=date1.getTime();
var time2=date2.getTime();
var totalMilisec=时间2-时间1;
警报(日期格式('hh:mm:ss',新日期(totalMilisec)))
/* ----------------------------------------------------------
*字段|完整形式|缩写形式
*  -------------|--------------------|-----------------------
*年份| yyyy(4位)| yy(2位)
*月|毫米(缩写)|毫米(两位数字)
|NNN(姓名)|
*月日|日(2位数字)|
*星期几| EE(姓名)| E(缩写)
*小时(1-12)|小时(2位数)|
*分钟|毫米(2位)|
*第二个| ss(2位)|
*  ----------------------------------------------------------
*/
函数日期格式(formatString,日期){
如果(日期类型=='undefined'){
var DateToFormat=新日期();
}
否则{
var DateToFormat=日期;
}
var DAY=DateToFormat.getDate();
var DAYidx=DateToFormat.getDay();
var MONTH=DateToFormat.getMonth()+1;
var MONTHidx=DateToFormat.getMonth();
var YEAR=DateToFormat.getYear();
var FULL_YEAR=DateToFormat.getFullYear();
var HOUR=DateToFormat.getHours();
var MINUTES=DateToFormat.getMinutes();
var SECONDS=DateToFormat.getSeconds();
var arrMonths=新数组(“一月”、“二月”、“三月”、“四月”、“五月”、“六月”、“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月”);
var arrDay=新数组(“星期日”、“星期一”、“星期二”、“星期三”、“星期四”、“星期五”、“星期六”);
var strMONTH;
var标准日;
瓦尔·斯特霍尔;
var-strMINUTES;
var-strSECONDS;
var分离器;
if(parseInt(MONTH)<10&&MONTH.toString().length<2)
strMONTH=“0”+月;
其他的
strMONTH=月份;
if(parseInt(DAY)<10&&DAY.toString().length<2)
strDAY=“0”+天;
其他的
标准日=天;
if(parseInt(HOUR)<10&&HOUR.toString().length<2)
strHOUR=“0”+小时;
其他的
strHOUR=小时;
if(parseInt(分钟)<10&&MINUTES.toString().length<2)
strmutes=“0”+分钟;
其他的
strmutes=分钟;
if(parseInt(秒)<10&&SECONDS.toString().length<2)
strSECONDS=“0”+秒;
其他的
strSECONDS=秒;
开关(格式化字符串){
案例“hh:mm:ss”:
返回strHOUR+':'+strMINUTES+':'+strSECONDS;
打破
//更多的情况下,以满足您的要求。
}
}

您也可以使用以下代码:

int ss = nDur%60;
nDur   = nDur/60;
int mm = nDur%60;
int hh = nDur/60;

下面是一个转换时间的简单函数,可能会有所帮助

function formatSeconds(seconds) {
    var date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}
正如Cleiton在中指出的,可用于:

moment().startOf('day')
        .seconds(15457)
        .format('H:mm:ss');
var timeInSec=“661”//甚至可以是字符串
String.prototype.toHHMMSS=函数(){
/*使用原型继承扩展字符串*/
var seconds=parseInt(这个,10);//不要忘记第二个参数
var小时=数学地板(秒/3600);
var分钟=数学地板((秒-(小时*3600))/60);
秒=秒-(小时*3600)-(分钟*60);
如果(小时<10){hours=“0”+小时;}
如果(分钟<10){minutes=“0”+分钟;}
如果(秒<10){seconds=“0”+秒;}
变量时间=小时+':'+分钟+':'+秒;
返回时间;
}
警报(“5678.toHHMMSS());//"01:34:38"
log(timeinset.toHHMMSS())//"00:11:01"
我们可以使这个函数更简短、更清晰,但这会降低可读性,因此我们将尽可能简单、稳定地编写它


或者您可以检查此工作状态:

您是否尝试过向日期对象添加秒数

Date.prototype.addSeconds = function(seconds) {
    this.setSeconds(this.getSeconds() + seconds);
};
var dt = new Date();
dt.addSeconds(1234);
样本:

更新:
示例链接丢失,因此我创建了一个新的链接。

您可以在不使用任何外部JavaScript库的情况下,借助JavaScript日期方法完成此操作,如下所示:

var date = new Date(null);
date.setSeconds(SECONDS); // specify value for SECONDS here
var result = date.toISOString().substr(11, 8);
或者,根据客户的意见;一行:

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

对于任何使用AngularJS的人来说,一个简单的解决方案是使用过滤值,它根据请求的格式将毫秒转换为字符串。例如:

<div>Offer ends in {{ timeRemaining | date: 'HH:mm:ss' }}</div>
优惠在{timeRemaining | date:'HH:mm:ss'}结束

请注意,这需要毫秒,因此如果从秒转换为秒(如原始问题所述),您可能需要将剩余时间乘以1000。

这里有一个函数,用于根据powtac的答案将秒转换为hh mm ss格式


适用于noobies的易用版本:

 var totalNumberOfSeconds = YOURNUMBEROFSECONDS;
 var hours = parseInt( totalNumberOfSeconds / 3600 );
 var minutes = parseInt( (totalNumberOfSeconds - (hours * 3600)) / 60 );
 var seconds = Math.floor((totalNumberOfSeconds - ((hours * 3600) + (minutes * 60))));
 var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);
 console.log(result);
var totalNumberOfSeconds=YOURNUMBEROFSECONDS;
var小时数=parseInt(总秒数/3600);
var minutes=parseInt((totalNumberOfSeconds-(hours*3600))/60);
var秒=数学地板((总秒数-((小时*3600)+(分钟*60));
var结果=(小时<10?“0”+小时:小时)+“:”+(分钟<10?“0”+分钟:分钟)+“:”+(秒<10?“0”+秒:秒);
控制台日志(结果);
试试这个:

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

这是Number类的一个扩展
var seconds = SecondsTohhmmss(70);
console.log(seconds);
// logs 00-01-10
 var totalNumberOfSeconds = YOURNUMBEROFSECONDS;
 var hours = parseInt( totalNumberOfSeconds / 3600 );
 var minutes = parseInt( (totalNumberOfSeconds - (hours * 3600)) / 60 );
 var seconds = Math.floor((totalNumberOfSeconds - ((hours * 3600) + (minutes * 60))));
 var result = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds  < 10 ? "0" + seconds : seconds);
 console.log(result);
function toTimeString(seconds) {
  return (new Date(seconds * 1000)).toUTCString().match(/(\d\d:\d\d:\d\d)/)[0];
}
function secsToTime(secs){
  var time = new Date(); 
  // create Date object and set to today's date and time
  time.setHours(parseInt(secs/3600) % 24);
  time.setMinutes(parseInt(secs/60) % 60);
  time.setSeconds(parseInt(secs%60));
  time = time.toTimeString().split(" ")[0];
  // time.toString() = "HH:mm:ss GMT-0800 (PST)"
  // time.toString().split(" ") = ["HH:mm:ss", "GMT-0800", "(PST)"]
  // time.toTimeString().split(" ")[0]; = "HH:mm:ss"
  return time;
}
var toHHMMSS = (secs) => {
    var sec_num = parseInt(secs, 10)
    var hours   = Math.floor(sec_num / 3600)
    var minutes = Math.floor(sec_num / 60) % 60
    var seconds = sec_num % 60

    return [hours,minutes,seconds]
        .map(v => v < 10 ? "0" + v : v)
        .filter((v,i) => v !== "00" || i > 0)
        .join(":")
}
toHHMMSS(129600) // 36:00:00
toHHMMSS(13545) // 03:45:45
toHHMMSS(180) // 03:00
toHHMMSS(18) // 00:18
var totalSec = new Date().getTime() / 1000;
var hours = parseInt( totalSec / 3600 ) % 24;
var minutes = parseInt( totalSec / 60 ) % 60;
var seconds = totalSec % 60;

var result = (hours < 10 ? "0" + hours : hours) + "-" + (minutes < 10 ? "0" + minutes : minutes) + "-" + (seconds  < 10 ? "0" + seconds : seconds);
25 % 24
25 mod 24 or what is the remainder when we divide 25 by 24
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
d=(s)=>{f=Math.floor;g=(n)=>('00'+n).slice(-2);return f(s/3600)+':'+g(f(s/60)%60)+':'+g(s%60)}
d(91260);     // returns "25:21:00"
d(960);       // returns "0:16:00"
var measuredTime = new Date(null);
measuredTime.setSeconds(4995); // specify value of SECONDS
var MHSTime = measuredTime.toISOString().substr(11, 8);
function formatSeconds(sec) {
     return [(sec / 3600), ((sec % 3600) / 60), ((sec % 3600) % 60)]
            .map(v => v < 10 ? "0" + parseInt(v) : parseInt(v))
            .filter((i, j) => i !== "00" || j > 0)
            .join(":");
}
function formatSeconds(sec) {
  return parseInt(sec / 3600) + ':' + parseInt((sec % 3600) / 60) + ':' + parseInt((sec % 3600) % 60);
secToHHMMSS = seconds => `${Math.floor(seconds / 3600)}:${Math.floor((seconds % 3600) / 60)}:${Math.floor((seconds % 3600) % 60)}`
secToDHHMMSS = seconds => `${parseInt(seconds / 86400)}d ${new Date(seconds * 1000).toISOString().substr(11, 8)}`
var sec_to_hms = function(sec){
var min, hours;
     sec = sec - (min = Math.floor(sec/60))*60;
     min = min - (hours = Math.floor(min/60))*60;
     return (hours?hours+':':'') + ((min+'').padStart(2, '0')) + ':'+ ((sec+'').padStart(2, '0'));
}
alert(sec_to_hms(2442542));
function secondsToTime(seconds) {
  const arr = new Date(seconds * 1000).toISOString().substr(11, 8).split(':');

  const days = Math.floor(seconds / 86400);
  arr[0] = parseInt(arr[0], 10) + days * 24;

  return arr.join(':');
}
secondsToTime(101596) // outputs '28:13:16' as opposed to '04:13:16'
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("186".toHHMMSS());
function secondsToTimeSpan(seconds) {
    const value = Math.abs(seconds);
    const days = Math.floor(value / 1440);
    const hours = Math.floor((value - (days * 1440)) / 3600);
    const min = Math.floor((value - (days * 1440) - (hours * 3600)) / 60);
    const sec = value - (days * 1440) - (hours * 3600) - (min * 60);
    return `${seconds < 0 ? '-':''}${days > 0 ? days + '.':''}${hours < 10 ? '0' + hours:hours}:${min < 10 ? '0' + min:min}:${sec < 10 ? '0' + sec:sec}`
}
secondsToTimeSpan(0);       // => 00:00:00
secondsToTimeSpan(1);       // => 00:00:01
secondsToTimeSpan(1440);    // => 1.00:00:00
secondsToTimeSpan(-1440);   // => -1.00:00:00
secondsToTimeSpan(-1);      // => -00:00:01
function hms(seconds) {
  return [3600, 60]
    .reduceRight(
      (pipeline, breakpoint) => remainder =>
        [Math.floor(remainder / breakpoint)].concat(pipeline(remainder % breakpoint)),
      r => [r]
    )(seconds)
    .map(amount => amount.toString().padStart(2, '0'))
    .join('-');
}
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"
function divideAndAppend(remainder, breakpoint, callback) {
  return [Math.floor(remainder / breakpoint)].concat(callback(remainder % breakpoint));
}
let pipeline = r3 => divideAndAppend(
    r3, 
    3600, 
    r2 => divideAndAppend(
        r2, 
        60, 
        r1 => [r1]));

> pipeline(3785)
< [1, 3, 5]
let breakpoints = [60, 3600];
let pipeline = r => [r];

for (const b of breakpoints) {
  const previousPipeline = pipeline;
  pipeline = r => divideAndAppend(r, b, previousPipeline);
}

> pipeline(3785)
< [1, 3, 5]
let pipeline = [60, 3600].reduce(
  (ppln, b) => r => divideAndAppend(r, b, ppln),
  r => [r]
);

> pipeline(3785)
< [1, 3, 5]
let pipeline = [3600, 60]
    .reduceRight(
      (ppln, b) => r => [Math.floor(r / b)].concat(ppln(r % b)),
      r => [r]
    );
function decompose(total, breakpoints) {
  return breakpoints.reduceRight(
    (p, b) => r => [Math.floor(r / b)].concat(p(r % b)),
    r => [r]
  )(total);
}

> decompose(3785, [3600, 60])
< [1, 3, 5]
function getHHMMSSFromSeconds(totalSeconds) {
    if (!totalSeconds) {
      return '00:00:00';
    }
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor(totalSeconds % 3600 / 60);
    const seconds = totalSeconds % 60;
    const hhmmss = padTo2(hours) + ':' + padTo2(minutes) + ':' + padTo2(seconds);
    return hhmmss;
}

// function to convert single digit to double digit
function padTo2(value) {
    if (!value) {
      return '00';
    }
    return value < 10 ? String(value).padStart(2, '0') : value;
}