Angular.js:秒数到HH:mm:ss过滤器 [英] Angular.js: Seconds to HH:mm:ss filter

查看:102
本文介绍了Angular.js:秒数到HH:mm:ss过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多秒数,例如713秒。如何实现将713秒转换为HH:mm:ss格式的Angular.js过滤器?在这种情况下,应为00:11:53

I have a number of seconds count, for example, 713 seconds. How can I implement an Angular.js filter that converts this 713 seconds to HH:mm:ss format? In this case, it should be 00:11:53

<div>
  {{ 713 | secondsToHHMMSS }} <!-- Should output 00:11:53 -->
</div>


推荐答案

manzapanza的答案仅在秒数小于86400时有效(1天)。日期对象必须完全为零。另外,最好返回实际的日期对象,以使angularjs不必再次创建它。

manzapanza's answer only works if the seconds are less than 86400 (1 day). The date object needs to be completely zero. Also, it would be better to return the actual date object so that angularjs does not have to make it again.

app.filter('secondsToDateTime', function() {
    return function(seconds) {
        var d = new Date(0,0,0,0,0,0,0);
        d.setSeconds(seconds);
        return d;
    };
});

<b>{{seconds | secondsToDateTime | date:'HH:mm:ss'}}</b>






编辑:如果如果您希望小时数超过24而又不浪费几天,最好不要使用Date:


If you want hours to go above 24 without wrapping to days it is better to not use Date:

app.filter('secondsToTime', function() {

    function padTime(t) {
        return t < 10 ? "0"+t : t;
    }

    return function(_seconds) {
        if (typeof _seconds !== "number" || _seconds < 0)
            return "00:00:00";

        var hours = Math.floor(_seconds / 3600),
            minutes = Math.floor((_seconds % 3600) / 60),
            seconds = Math.floor(_seconds % 60);

        return padTime(hours) + ":" + padTime(minutes) + ":" + padTime(seconds);
    };
});

<b>{{seconds | secondsToTime}}</b>

这篇关于Angular.js:秒数到HH:mm:ss过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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