English 中文(简体)
• with版向HHHH-MM-SS转秒?
原标题:Convert seconds to HH-MM-SS with JavaScript?
  • 时间:2009-08-24 14:26:56
  •  标签:

我如何将二字改为<条码> HH-MM-SSstring using Java texts?

最佳回答

<>Updated (2020):

请使用@Frank 一条线解决办法:

new Date(SECONDS * 1000).toISOString().substring(11, 16)

如果你只想显示MM:SS 然后使用以下代码:

new Date(SECONDS * 1000).toISOString().substring(14, 19)

这是迄今为止的最佳解决办法。


http://www.hchr.org。

使用http://momentjs.com” rel=“noreferer”>Moment.js 图书馆。

问题回答

如果没有外部的贾瓦文图书馆,在贾瓦古斯塔语时代方法的帮助下,你可以这样做:

const date = new Date(null);
date.setSeconds(SECONDS); // specify value for SECONDS here
const result = date.toISOString().slice(11, 19);

Frank 评论;一行:

new Date(SECONDS * 1000).toISOString().slice(11, 19);

我不认为标准日期目标的任何内在特点,都会使你更方便地这样做,而不是仅仅做数学。

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

例:

let totalSeconds = 28565;
let hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
let minutes = Math.floor(totalSeconds / 60);
let seconds = totalSeconds % 60;

console.log("hours: " + hours);
console.log("minutes: " + minutes);
console.log("seconds: " + seconds);

// If you want strings with leading zeroes:
minutes = String(minutes).padStart(2, "0");
hours = String(hours).padStart(2, "0");
seconds = String(seconds).padStart(2, "0");
console.log(hours + ":" + minutes + ":" + seconds);

我知道这有点旧了,但是...

ES2015:

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

这里简单的功能是转换时间,可以帮助

function formatSeconds(seconds) {
    var date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(d{2}:d{2}:d{2}).*/, "$1");
}
var  timeInSec = "661"; //even it can be string

String.prototype.toHHMMSS = function () { 
   /* extend the String by using prototypical inheritance */
    var seconds = parseInt(this, 10); // don t forget the second param
    var hours   = Math.floor(seconds / 3600);
    var minutes = Math.floor((seconds - (hours * 3600)) / 60);
    seconds = seconds - (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;
}

alert("5678".toHHMMSS());   // "01:34:38"
console.log(timeInSec.toHHMMSS());   //"00:11:01"

我们能够使这一职能缩短很多,缩小可读性,这样,我们将尽可能简明扼要,尽可能稳定。

http://fiddle.jshell.net/sahilosheal/N2B5J/“rel=“nofollow noreferer” 职称=“example”

我认为,最普遍的(和加密)解决办法可能是这样。

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"

How it works

Algorithm

  1. To get hours you divide total seconds by 3600 and floor it.
  2. To get minutes you divide remainder by 60 and floor it.
  3. To get seconds you just use the remainder.

还必须把个人数量保持在一个阵列中,以便于格式化。

例如,鉴于3785年代的投入,产出应为<代码>[1、3、5],即1小时、3分钟和5秒。

Creating pipeline

将3600和60个不变的“突破点”命名为“突破点”,你可以将这一算法写成功能。

function divideAndAppend(remainder, breakpoint, callback) {
  return [Math.floor(remainder / breakpoint)].concat(callback(remainder % breakpoint));
}

It returns an array where first item is the amount for given breakpoint and the rest of the array is given by the callback. Reusing the divideAndAppend in callback function will give you a pipeline of composed divideAndAppend functions. Each one of these computes amount per given breakpoint and append it to the array making your desired output.

Then you also need the "final" callback that ends this pipeline. In another words you used all breakpoints and now you have only the remainder. Since you have already the answer at 3) you should use some sort of identity function, in this case remainder => [remainder].

你们现在可以照此写管道。

let pipeline = r3 => divideAndAppend(
    r3, 
    3600, 
    r2 => divideAndAppend(
        r2, 
        60, 
        r1 => [r1]));

> pipeline(3785)
< [1, 3, 5]

冷静的权利?

Generalizing using for-loop

Now you can generalize with a variable amount of breakpoints and create a for-loop that will compose individial divideAndAppend functions into the pipeline. You start with the identity function r1 => [r1], then use the 60 breakpoint and finally use the 3600 breakpoint.

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]

Using Array.prototype.reduce()

现在,你可以把这种 for改成更短、更实用的法典。 换言之,将职能构成改为减员。

let pipeline = [60, 3600].reduce(
  (ppln, b) => r => divideAndAppend(r, b, ppln),
  r => [r]
);

> pipeline(3785)
< [1, 3, 5]

浏览器<代码>ppln为输油管,你正在使用以前的版本进行堆积。 最初的管道是r => [r]

You can now inline the function divideAndAppend and use Array.prototype.reduceRight which is the same as [].reverse().reduce(...) to make the breakpoints definitions more natural.

let pipeline = [3600, 60]
    .reduceRight(
      (ppln, b) => r => [Math.floor(r / b)].concat(ppln(r % b)),
      r => [r]
    );

最后形式。 然后,你只读地图,在左边铺设零件,并加入带<代码>的座标:分离器;

More generalizations

将减员用于功能

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]

现在,你可以采用非常一般的算法。 例如:

Convert easily (the weird) us length standards

鉴于标准

Unit Divisions
1 foot 12 inches
1 yard 3 feet
1 mile 1760 yards
> decompose(123_456, [1760 * 3 * 12, 3 * 12, 12])
< [1, 1669, 1, 0]

页: 1

Or you can somewhat convert to decimal or binary representations

> decompose(123_456, [100_000, 10_000, 1000, 100, 10])
< [1, 2, 3, 4, 5, 6]

> decompose(127, [128, 64, 32, 16, 8, 4, 2])
< [0, 1, 1, 1, 1, 1, 1, 1]

Works also with floating point breakpoints

由于 Java印支持<代码>mod的操作者,并注明点号,你也可以这样做。

> decompose(26.5, [20, 2.5])
< [1, 2, 1.5]

The edge case of no breakpoints is also naturally covered

> decompose(123, [])
< [123]

为此:

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

Here is an extension to Number class. toHHMMSS() converts seconds to an hh:mm:ss string.

Number.prototype.toHHMMSS = function() {
  var hours = Math.floor(this / 3600) < 10 ? ("00" + Math.floor(this / 3600)).slice(-2) : Math.floor(this / 3600);
  var minutes = ("00" + Math.floor((this % 3600) / 60)).slice(-2);
  var seconds = ("00" + (this % 3600) % 60).slice(-2);
  return hours + ":" + minutes + ":" + seconds;
}

// Usage: [number variable].toHHMMSS();

// Here is a simple test
var totalseconds = 1234;
document.getElementById("timespan").innerHTML = totalseconds.toHHMMSS();
// HTML of the test
<div id="timespan"></div>

2. 便于查阅:

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

在这一古老的路面上,在你意识到需要超过24小时之前,欧佩组织称HH:MM:SS和许多解决办法工作。 也许,你们不希望超过一条单一的法典。 各位:

d=(s)=>{f=Math.floor;g=(n)=>( 00 +n).slice(-2);return f(s/3600)+ : +g(f(s/60)%60)+ : +g(s%60)}

它返回了H+:MM:SS。 仅使用:

d(91260);     // returns "25:21:00"
d(960);       // returns "0:16:00"

...... 我试图使其尽可能少使用法典,以便采用单行办法。

www.un.org/Depts/DGACM/index_french.htm HH:MM:SS.MS (eq: “00:04:33.637”) as used by FFMPEG to specified milliseconds

[-][H:]MM:SS[m...]

HH expresses the number of hours, MM the number of minutes for a maximum of 2 digits, and SS the number of seconds for a maximum of 2 digits. The m at the end expresses decimal value for SS.

/* HH:MM:SS.MS to (FLOAT)seconds ---------------*/
function timerToSec(timer){
   let vtimer = timer.split(":")
   let vhours = +vtimer[0]
   let vminutes = +vtimer[1]
   let vseconds = parseFloat(vtimer[2])
   return vhours * 3600 + vminutes * 60 + vseconds
}

/* Seconds to (STRING)HH:MM:SS.MS --------------*/
function secToTimer(sec){
  let o = new Date(0)
  let p =  new Date(sec*1000)  
  return new Date(p.getTime()-o.getTime())
    .toISOString()
    .split("T")[1]
    .split("Z")[0]
}

/* Example: 7hours, 4 minutes, 33 seconds and 637 milliseconds */
const t = "07:04:33.637"
console.log(
  t + " => " +
  timerToSec(t) +
  "s"
)

/* Test: 25473 seconds and 637 milliseconds */
const s = 25473.637 // "25473.637"
console.log(
  s + "s => " + 
  secToTimer(s)
)

www.un.org/Depts/DGACM/index_spanish.htm 例使用,一毫秒运输时间:

/* Seconds to (STRING)HH:MM:SS.MS --------------*/
function secToTimer(sec){
  let o = new Date(0)
  let p =  new Date(sec*1000)  
  return new Date(p.getTime()-o.getTime())
    .toISOString()
    .split("T")[1]
    .split("Z")[0]
}

let job, origin = new Date().getTime()
const timer = () => {
  job = requestAnimationFrame(timer)
  OUT.textContent = secToTimer((new Date().getTime() - origin) / 1000)
}

requestAnimationFrame(timer)
span {font-size:4rem}
<span id="OUT"></span>
<br>
<button onclick="origin = new Date().getTime()">RESET</button>
<button onclick="requestAnimationFrame(timer)">RESTART</button>
<button onclick="cancelAnimationFrame(job)">STOP</button>

www.un.org/Depts/DGACM/index_spanish.htm 例使用,受媒体因素约束:

/* Seconds to (STRING)HH:MM:SS.MS --------------*/
function secToTimer(sec){
  let o = new Date(0)
  let p =  new Date(sec*1000)  
  return new Date(p.getTime()-o.getTime())
    .toISOString()
    .split("T")[1]
    .split("Z")[0]
}

VIDEO.addEventListener("timeupdate", function(e){
  OUT.textContent = secToTimer(e.target.currentTime)
}, false)
span {font-size:4rem}
<span id="OUT"></span><br>
<video id="VIDEO" width="400" controls autoplay>
  <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
</video>

在问题之外,这些职能在网址上写成:

<?php 
/* HH:MM:SS to (FLOAT)seconds ------------------*/
function timerToSec($timer){
  $vtimer = explode(":",$timer);
  $vhours = (int)$vtimer[0];
  $vminutes = (int)$vtimer[1];
  $vseconds = (float)$vtimer[2];
  return $vhours * 3600 + $vminutes * 60 + $vseconds;
}
/* Seconds to (STRING)HH:MM:SS -----------------*/
function secToTimer($sec){
  return explode(" ", date("H:i:s", $sec))[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;
}

我设定了一个新日期,将时间改为我的参数,将日期对时间表示反对,并且只将扼杀部分分开,只将需要的部分退回,从而消除了额外的障碍。

我认为,我赞同这种做法,因为这种办法排除了以“HH:mm:s”形式取得结果所需要的reg、逻辑和数学分母,而是依靠在方法上建立。

您不妨研究以下文件:

简单功能将二秒转换成h:毫米:格式

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;
}
var time1 = date1.getTime();
var time2 = date2.getTime();
var totalMilisec = time2 - time1;

alert(DateFormat( hh:mm:ss ,new Date(totalMilisec)))

 /* ----------------------------------------------------------
 *  Field        | Full Form          | Short Form
 *  -------------|--------------------|-----------------------
 *  Year         | yyyy (4 digits)    | yy (2 digits)
 *  Month        | MMM (abbr.)        | MM (2 digits)
                 | NNN (name)         |
 *  Day of Month | dd (2 digits)      | 
 *  Day of Week  | EE (name)          | E (abbr)
 *  Hour (1-12)  | hh (2 digits)      | 
 *  Minute       | mm (2 digits)      | 
 *  Second       | ss (2 digits)      | 
 *  ----------------------------------------------------------
 */
function DateFormat(formatString,date){
    if (typeof date== undefined ){
    var DateToFormat=new Date();
    }
    else{
        var DateToFormat=date;
    }
    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 = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
    var arrDay=new Array( Sunday , Monday , Tuesday , Wednesday , Thursday , Friday , Saturday );
    var strMONTH;
    var strDAY;
    var strHOUR;
    var strMINUTES;
    var strSECONDS;
    var Separator;

    if(parseInt(MONTH)< 10 && MONTH.toString().length < 2)
        strMONTH = "0" + MONTH;
    else
        strMONTH=MONTH;
    if(parseInt(DAY)< 10 && DAY.toString().length < 2)
        strDAY = "0" + DAY;
    else
        strDAY=DAY;
    if(parseInt(HOUR)< 10 && HOUR.toString().length < 2)
        strHOUR = "0" + HOUR;
    else
        strHOUR=HOUR;
    if(parseInt(MINUTES)< 10 && MINUTES.toString().length < 2)
        strMINUTES = "0" + MINUTES;
    else
        strMINUTES=MINUTES;
    if(parseInt(SECONDS)< 10 && SECONDS.toString().length < 2)
        strSECONDS = "0" + SECONDS;
    else
        strSECONDS=SECONDS;

    switch (formatString){
        case "hh:mm:ss":
            return strHOUR +  :  + strMINUTES +  :  + strSECONDS;
        break;
        //More cases to meet your requirements.
    }
}

我只想对上述雄辩回答作些什么解释:

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

在第二行,由于1小时有3 600秒,我们把第二位数的总数从3600分到3600分,以达到总时数。 我们利用教区来切断任何污点。 如果Sec的总数为12600(3小时半小时),那么PaleInt(总计为3600小时)就会返回3小时,因为我们将有3个全职时间。 为什么在这种情况下我们需要24 %? 如果我们超过24小时,请说我们有25小时(90000秒),那么这里的单元将使我们再次回到1小时,而不是回到25小时。 由于一天24小时,结果在24小时之内被限制。

当你看到这样的情况:

25 % 24

想这样做:

25 mod 24 or what is the remainder when we divide 25 by 24

这里的任何答复都不符合我的要求,因为我想要能够处理。

  1. Large numbers of seconds (days), and
  2. Negative numbers

尽管《任择议定书》并不要求这样做,但它在涵盖边际案件方面,尤其是在几乎没有努力的情况下,是良好做法。

很显然的是,《任择议定书》是指他在seconds上说的第二秒钟。 为什么要把你的职能放在<条码>上?

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

这里的一个功能是,根据回答here

rel=“nofollow noreferer”>jsfiddle

/** 
 * Convert seconds to hh-mm-ss format.
 * @param {number} totalSeconds - the total seconds to convert to hh- mm-ss
**/
var SecondsTohhmmss = function(totalSeconds) {
  var hours   = Math.floor(totalSeconds / 3600);
  var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
  var seconds = totalSeconds - (hours * 3600) - (minutes * 60);

  // round seconds
  seconds = Math.round(seconds * 100) / 100

  var result = (hours < 10 ? "0" + hours : hours);
      result += "-" + (minutes < 10 ? "0" + minutes : minutes);
      result += "-" + (seconds  < 10 ? "0" + seconds : seconds);
  return result;
}

例 例

var seconds = SecondsTohhmmss(70);
console.log(seconds);
// logs 00-01-10

解决这一问题有很多选择,显然有很好的选择,但我想在此增加一个更为优化的法典。

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(":");
iii

如果你不希望零格式,再少10个。

function formatSeconds(sec) {
  return parseInt(sec / 3600) +  :  + parseInt((sec % 3600) / 60) +  :  + parseInt((sec % 3600) % 60);

iii

Sample Code

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));
export const secondsToHHMMSS = (seconds) => {
  const HH = `${Math.floor(seconds / 3600)}`.padStart(2,  0 );
  const MM = `${Math.floor(seconds / 60) % 60}`.padStart(2,  0 );
  const SS = `${Math.floor(seconds % 60)}`.padStart(2,  0 );
  return [HH, MM, SS].join( : );
};

也可以使用以下法典:

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

有些人提到,借调人数超过一天。 这里的“Harish Anchu”这一经过修改的回答是:

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 




相关问题
热门标签