用JavaScript将秒转换成hh - ms - ss ?

时间:2022-06-28 02:49:29

How can I convert seconds to an HH-MM-SS string using JavaScript?

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

27 个解决方案

#1


91  

Don't you know datejs? it is a must know.

难道你不知道datejs吗?这是必须知道的。

Using datejs, just write something like:

使用datejs,只需编写如下内容:

(new Date).clearTime()
          .addSeconds(15457)
          .toString('H:mm:ss');

--update

- - -更新

Nowadays date.js is outdated and not maintained, so use "Moment.js", which is much better as pointed out by T.J. Crowder.

现在的日期。js过时了,没有维护,所以使用“Moment”。正如T.J.克劳德所指出的那样。

#2


227  

You can manage to do this without any external JavaScript library with the help of JavaScript Date method like following:

在JavaScript日期方法的帮助下,您可以在没有任何外部JavaScript库的情况下做到这一点:

var date = new Date(null);
date.setSeconds(SECONDS); // specify value for SECONDS here
var result = date.toISOString().substr(11, 8);

#3


83  

I don't think any built-in feature of the standard Date object will do this for you in a way that's more convenient than just doing the math yourself.

我不认为标准日期对象的任何内置特性会比你自己做计算更方便。

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

#4


25  

As Cleiton pointed out in his answer, moment.js can be used for this:

正如Cleiton在他的回答中指出的那样。js可用于此:

moment().startOf('day')
        .seconds(15457)
        .format('H:mm:ss');

#5


16  

function formatSeconds(seconds)
{
    var date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}

#6


16  

I know this is kinda old, but...

我知道这有点老,但是…

ES2015:

ES2015:

var toHHMMSS = (secs) => {
    var sec_num = parseInt(secs, 10)    
    var hours   = Math.floor(sec_num / 3600) % 24
    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(":")
}

It will output:

它将输出:

toHHMMSS(13545) // 03:45:45
toHHMMSS(180) // 03:00
toHHMMSS(18) // 00:18

#7


13  

This does the trick:

这个诀窍:

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

(Sourced from here)

(来自)

#8


8  

Try this:

试试这个:

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

#9


6  

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

这是给Number类的一个扩展。toHHMMSS()将秒转换为hh:mm:ss字符串。

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>

#10


5  

     var  timeInSec = "661"; //even it can be string
            String.prototype.toHHMMSS = function () { 
    /* extend the String by using prototypical inheritance,
 so that you can use it to any string directly across all your app. */
                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);
                var 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());
            console.log(timeInSec.toHHMMSS());

or you can check this working here: http://fiddle.jshell.net/sahilosheal/N2B5J/

或者您可以在这里查看这个工作:http://fiddle.jshell.net/sahilosheal/N2B5J/。

#11


4  

This function should do it :

这个函数应该这样做:

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

Without passing a separator, it uses : as the (default) separator :

没有传递分隔符,它使用:作为(默认)分隔符:

time = convertTime(13551.9941351); // --> OUTPUT = 03:45:51

If you want to use - as a separator, just pass it as the second parameter:

如果您想使用-作为一个分隔符,请将它作为第二个参数传递:

time = convertTime(1126.5135155, '-'); // --> OUTPUT = 00-18-46

See also this Fiddle.

看到这个小提琴也。

#12


4  

below is the given code which will convert seconds into hh-mm-ss format:

下面是给定的代码,该代码将把秒转换为hh-mm-ss格式:

var measuredTime = new Date(null);
measuredTime.setSeconds(4995); // specify value of SECONDS
var MHSTime = measuredTime.toISOString().substr(11, 8);

Get alternative method from Convert seconds to HH-MM-SS format in JavaScript

从转换秒到HH-MM-SS格式的JavaScript中获得替代方法。

#13


3  

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

#14


3  

Easy to follow version for noobies:

易于遵循的版本为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);

#15


3  

I just wanted to give a little explanation to the nice answer above:

我只是想解释一下上面这个漂亮的答案:

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

On the second line, since there are 3600 seconds in 1 hour, we divide the total number of seconds by 3600 to get the total number of hours. We use parseInt to strip off any decimal. If totalSec was 12600 (3 and half hours), then parseInt( totalSec / 3600 ) would return 3, since we will have 3 full hours. Why do we need the % 24 in this case? If we exceed 24 hours, let's say we have 25 hours (90000 seconds), then the modulo here will take us back to 1 again, rather than returning 25. It is confining the result within a 24 hour limit, since there are 24 hours in one day.

在第二行,因为在1小时内有3600秒,我们将总秒数除以3600,得到总小时数。我们使用parseInt去掉任何小数。如果totalSec是12600(3个半小时),那么parseInt(totalSec / 3600)将返回3,因为我们将有3个小时。在这种情况下,为什么我们需要% 24 ?如果我们超过24小时,假设我们有25小时(90000秒),那么这里的模块会把我们带回到1,而不是返回25。因为一天有24小时,所以限制了24小时内的结果。

When you see something like this:

当你看到这样的东西:

25 % 24

Think of it like this:

可以这样想:

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

#16


3  

Chiming in on this old thread -- the OP stated HH:MM:SS, and many of the solutions work, until you realize you need more than 24 hours listed. And maybe you don't want more than a single line of code. Here you go:

在这个旧的线程上插话——OP声明HH:MM:SS,以及许多解决方案工作,直到您意识到您需要超过24小时的列表。也许你不需要超过一行代码。给你:

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

It returns H+:MM:SS. To use it, simply use:

它返回H +:MM:SS。要使用它,只需使用:

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

...I tried to get it to use the least amount of code possible, for a nice one-liner approach.

…我试图让它使用尽可能少的代码,这是一种很好的一行代码方法。

#17


2  

Here is a function to convert seconds to hh-mm-ss format based on powtac's answer here

这里有一个函数,根据powtac的回答,将秒转换为hh-mm-ss格式。

jsfiddle

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

Example use

示例使用

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

#18


2  

After looking at all the answers and not being happy with most of them, this is what I came up with. I know I am very late to the conversation, but here it is anyway.

看完所有的答案后,我对大部分的答案都不满意,这就是我想到的。我知道我的谈话很晚了,但不管怎样,这就是我要说的。

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

I create a new Date object, change the time to my parameters, convert the Date Object to a time string, and removed the additional stuff by splitting the string and returning only the part that need.

我创建了一个新的日期对象,将时间更改为参数,将日期对象转换为一个时间字符串,并通过分割字符串并只返回需要的部分来删除额外的内容。

I thought I would share this approach, since it removes the need for regex, logic and math acrobatics to get the results in "HH:mm:ss" format, and instead it relies on built in methods.

我想我应该分享这个方法,因为它消除了regex、逻辑和数学杂技的需要,以得到“HH:mm:ss”格式的结果,而不是依赖于方法的构建。

You may want to take a look at the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

您可能想看一下这里的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date。

#19


2  

There are lots of options of solve this problem, and obvious there are good option suggested about, But I wants to add one more optimized code here

有很多解决这个问题的选项,显然有很好的选择,但是我想在这里添加一个更优化的代码。

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

if you don't wants formatted zero with less then 10 number, you can use

如果您不希望格式化为0,那么您可以使用以下10个数字。

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

}

}

Sample Code http://fiddly.org/1c476/1

示例代码http://fiddly.org/1c476/1

#20


1  

You can also use below code:

你也可以使用以下代码:

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

#21


1  

Have you tried adding seconds to a Date object?

你试过在日期对象上添加秒吗?

var dt = new Date();
dt.addSeconds(1234);

A sample: http://fiddle.jshell.net/YvE7x/2/

一个示例:http://fiddle.jshell.net/YvE7x/2/

#22


1  

For anyone using AngularJS, a simple solution is to filter the value with the date API, which converts milliseconds to a string based on the requested format. Example:

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

<div>Offer ends in {{ timeRemaining | date: 'HH:mm:ss' }}</div>

Note that this expects milliseconds, so you may want to multiply timeRemaining by 1000 if you are converting from seconds (as the original question was formulated).

注意,这个期望是毫秒,所以如果您从秒开始转换,那么您可能想要将timeRemaining乘以1000(因为最初的问题已经被制定出来了)。

#23


1  

In one line, using T.J. Crowder's solution :

在一行中,使用T.J.克劳德的解决方案:

secToHHMMSS = seconds => `${Math.floor(seconds / 3600)}:${Math.floor((seconds % 3600) / 60)}:${Math.floor((seconds % 3600) % 60)}`

In one line, another solution that also count days :

在一行中,另一种解决方案也计算天数:

secToDHHMMSS = seconds => `${parseInt(seconds / 86400)}d ${new Date(seconds * 1000).toISOString().substr(11, 8)}`

Source : https://gist.github.com/martinbean/2bf88c446be8048814cf02b2641ba276

来源:https://gist.github.com/martinbean/2bf88c446be8048814cf02b2641ba276

#24


0  

I've used this code before to create a simple timespan object:

我以前用过这个代码来创建一个简单的timespan对象:

function TimeSpan(time) {
this.hours = 0;
this.minutes = 0;
this.seconds = 0;

while(time >= 3600)
{
    this.hours++;
    time -= 3600;
}

while(time >= 60)
{
    this.minutes++;
    time -= 60;
}

this.seconds = time;
}

var timespan = new Timespan(3662);

#25


-1  

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

新的日期().toString()。分割(" ")[4];

result 15:08:03

结果15:08:03

#26


-1  

You can also use Sugar.

你也可以用糖。

Date.create().reset().set({seconds: 180}).format('{mm}:{ss}');

This example returns '03:00'.

这个示例返回“03:00”。

#27


-1  

using momentjs for singleday calculation

使用momentjs进行单次计算。

var number = 10000(milliseconds); 
var momentObject = moment.duration(number);  

var output =  momentObject.hours()+"HH"+momentObject.minutes()+"MM"+minuteObject.seconds()+"S" 

#1


91  

Don't you know datejs? it is a must know.

难道你不知道datejs吗?这是必须知道的。

Using datejs, just write something like:

使用datejs,只需编写如下内容:

(new Date).clearTime()
          .addSeconds(15457)
          .toString('H:mm:ss');

--update

- - -更新

Nowadays date.js is outdated and not maintained, so use "Moment.js", which is much better as pointed out by T.J. Crowder.

现在的日期。js过时了,没有维护,所以使用“Moment”。正如T.J.克劳德所指出的那样。

#2


227  

You can manage to do this without any external JavaScript library with the help of JavaScript Date method like following:

在JavaScript日期方法的帮助下,您可以在没有任何外部JavaScript库的情况下做到这一点:

var date = new Date(null);
date.setSeconds(SECONDS); // specify value for SECONDS here
var result = date.toISOString().substr(11, 8);

#3


83  

I don't think any built-in feature of the standard Date object will do this for you in a way that's more convenient than just doing the math yourself.

我不认为标准日期对象的任何内置特性会比你自己做计算更方便。

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

#4


25  

As Cleiton pointed out in his answer, moment.js can be used for this:

正如Cleiton在他的回答中指出的那样。js可用于此:

moment().startOf('day')
        .seconds(15457)
        .format('H:mm:ss');

#5


16  

function formatSeconds(seconds)
{
    var date = new Date(1970,0,1);
    date.setSeconds(seconds);
    return date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");
}

#6


16  

I know this is kinda old, but...

我知道这有点老,但是…

ES2015:

ES2015:

var toHHMMSS = (secs) => {
    var sec_num = parseInt(secs, 10)    
    var hours   = Math.floor(sec_num / 3600) % 24
    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(":")
}

It will output:

它将输出:

toHHMMSS(13545) // 03:45:45
toHHMMSS(180) // 03:00
toHHMMSS(18) // 00:18

#7


13  

This does the trick:

这个诀窍:

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

(Sourced from here)

(来自)

#8


8  

Try this:

试试这个:

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

#9


6  

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

这是给Number类的一个扩展。toHHMMSS()将秒转换为hh:mm:ss字符串。

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>

#10


5  

     var  timeInSec = "661"; //even it can be string
            String.prototype.toHHMMSS = function () { 
    /* extend the String by using prototypical inheritance,
 so that you can use it to any string directly across all your app. */
                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);
                var 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());
            console.log(timeInSec.toHHMMSS());

or you can check this working here: http://fiddle.jshell.net/sahilosheal/N2B5J/

或者您可以在这里查看这个工作:http://fiddle.jshell.net/sahilosheal/N2B5J/。

#11


4  

This function should do it :

这个函数应该这样做:

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

Without passing a separator, it uses : as the (default) separator :

没有传递分隔符,它使用:作为(默认)分隔符:

time = convertTime(13551.9941351); // --> OUTPUT = 03:45:51

If you want to use - as a separator, just pass it as the second parameter:

如果您想使用-作为一个分隔符,请将它作为第二个参数传递:

time = convertTime(1126.5135155, '-'); // --> OUTPUT = 00-18-46

See also this Fiddle.

看到这个小提琴也。

#12


4  

below is the given code which will convert seconds into hh-mm-ss format:

下面是给定的代码,该代码将把秒转换为hh-mm-ss格式:

var measuredTime = new Date(null);
measuredTime.setSeconds(4995); // specify value of SECONDS
var MHSTime = measuredTime.toISOString().substr(11, 8);

Get alternative method from Convert seconds to HH-MM-SS format in JavaScript

从转换秒到HH-MM-SS格式的JavaScript中获得替代方法。

#13


3  

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

#14


3  

Easy to follow version for noobies:

易于遵循的版本为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);

#15


3  

I just wanted to give a little explanation to the nice answer above:

我只是想解释一下上面这个漂亮的答案:

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

On the second line, since there are 3600 seconds in 1 hour, we divide the total number of seconds by 3600 to get the total number of hours. We use parseInt to strip off any decimal. If totalSec was 12600 (3 and half hours), then parseInt( totalSec / 3600 ) would return 3, since we will have 3 full hours. Why do we need the % 24 in this case? If we exceed 24 hours, let's say we have 25 hours (90000 seconds), then the modulo here will take us back to 1 again, rather than returning 25. It is confining the result within a 24 hour limit, since there are 24 hours in one day.

在第二行,因为在1小时内有3600秒,我们将总秒数除以3600,得到总小时数。我们使用parseInt去掉任何小数。如果totalSec是12600(3个半小时),那么parseInt(totalSec / 3600)将返回3,因为我们将有3个小时。在这种情况下,为什么我们需要% 24 ?如果我们超过24小时,假设我们有25小时(90000秒),那么这里的模块会把我们带回到1,而不是返回25。因为一天有24小时,所以限制了24小时内的结果。

When you see something like this:

当你看到这样的东西:

25 % 24

Think of it like this:

可以这样想:

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

#16


3  

Chiming in on this old thread -- the OP stated HH:MM:SS, and many of the solutions work, until you realize you need more than 24 hours listed. And maybe you don't want more than a single line of code. Here you go:

在这个旧的线程上插话——OP声明HH:MM:SS,以及许多解决方案工作,直到您意识到您需要超过24小时的列表。也许你不需要超过一行代码。给你:

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

It returns H+:MM:SS. To use it, simply use:

它返回H +:MM:SS。要使用它,只需使用:

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

...I tried to get it to use the least amount of code possible, for a nice one-liner approach.

…我试图让它使用尽可能少的代码,这是一种很好的一行代码方法。

#17


2  

Here is a function to convert seconds to hh-mm-ss format based on powtac's answer here

这里有一个函数,根据powtac的回答,将秒转换为hh-mm-ss格式。

jsfiddle

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

Example use

示例使用

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

#18


2  

After looking at all the answers and not being happy with most of them, this is what I came up with. I know I am very late to the conversation, but here it is anyway.

看完所有的答案后,我对大部分的答案都不满意,这就是我想到的。我知道我的谈话很晚了,但不管怎样,这就是我要说的。

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

I create a new Date object, change the time to my parameters, convert the Date Object to a time string, and removed the additional stuff by splitting the string and returning only the part that need.

我创建了一个新的日期对象,将时间更改为参数,将日期对象转换为一个时间字符串,并通过分割字符串并只返回需要的部分来删除额外的内容。

I thought I would share this approach, since it removes the need for regex, logic and math acrobatics to get the results in "HH:mm:ss" format, and instead it relies on built in methods.

我想我应该分享这个方法,因为它消除了regex、逻辑和数学杂技的需要,以得到“HH:mm:ss”格式的结果,而不是依赖于方法的构建。

You may want to take a look at the documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

您可能想看一下这里的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date。

#19


2  

There are lots of options of solve this problem, and obvious there are good option suggested about, But I wants to add one more optimized code here

有很多解决这个问题的选项,显然有很好的选择,但是我想在这里添加一个更优化的代码。

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

if you don't wants formatted zero with less then 10 number, you can use

如果您不希望格式化为0,那么您可以使用以下10个数字。

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

}

}

Sample Code http://fiddly.org/1c476/1

示例代码http://fiddly.org/1c476/1

#20


1  

You can also use below code:

你也可以使用以下代码:

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

#21


1  

Have you tried adding seconds to a Date object?

你试过在日期对象上添加秒吗?

var dt = new Date();
dt.addSeconds(1234);

A sample: http://fiddle.jshell.net/YvE7x/2/

一个示例:http://fiddle.jshell.net/YvE7x/2/

#22


1  

For anyone using AngularJS, a simple solution is to filter the value with the date API, which converts milliseconds to a string based on the requested format. Example:

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

<div>Offer ends in {{ timeRemaining | date: 'HH:mm:ss' }}</div>

Note that this expects milliseconds, so you may want to multiply timeRemaining by 1000 if you are converting from seconds (as the original question was formulated).

注意,这个期望是毫秒,所以如果您从秒开始转换,那么您可能想要将timeRemaining乘以1000(因为最初的问题已经被制定出来了)。

#23


1  

In one line, using T.J. Crowder's solution :

在一行中,使用T.J.克劳德的解决方案:

secToHHMMSS = seconds => `${Math.floor(seconds / 3600)}:${Math.floor((seconds % 3600) / 60)}:${Math.floor((seconds % 3600) % 60)}`

In one line, another solution that also count days :

在一行中,另一种解决方案也计算天数:

secToDHHMMSS = seconds => `${parseInt(seconds / 86400)}d ${new Date(seconds * 1000).toISOString().substr(11, 8)}`

Source : https://gist.github.com/martinbean/2bf88c446be8048814cf02b2641ba276

来源:https://gist.github.com/martinbean/2bf88c446be8048814cf02b2641ba276

#24


0  

I've used this code before to create a simple timespan object:

我以前用过这个代码来创建一个简单的timespan对象:

function TimeSpan(time) {
this.hours = 0;
this.minutes = 0;
this.seconds = 0;

while(time >= 3600)
{
    this.hours++;
    time -= 3600;
}

while(time >= 60)
{
    this.minutes++;
    time -= 60;
}

this.seconds = time;
}

var timespan = new Timespan(3662);

#25


-1  

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

新的日期().toString()。分割(" ")[4];

result 15:08:03

结果15:08:03

#26


-1  

You can also use Sugar.

你也可以用糖。

Date.create().reset().set({seconds: 180}).format('{mm}:{ss}');

This example returns '03:00'.

这个示例返回“03:00”。

#27


-1  

using momentjs for singleday calculation

使用momentjs进行单次计算。

var number = 10000(milliseconds); 
var momentObject = moment.duration(number);  

var output =  momentObject.hours()+"HH"+momentObject.minutes()+"MM"+minuteObject.seconds()+"S"