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

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

问题描述

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

{{ 713 |secondsToHHMMSS }} <!-- 应该输出 00:11:53 -->

解决方案

manzapanza 的回答仅适用于秒数小于 86400(1 天)的情况.日期对象需要完全为零.另外,最好返回实际的日期对象,这样 angularjs 就不必再次创建它.

app.filter('secondsToDateTime', function() {返回函数(秒){var d = 新日期(0,0,0,0,0,0,0);d.setSeconds(秒);返回d;};});

{{秒 |秒到日期时间 |日期:'HH:mm:ss'}}</b>

<小时>

如果您希望小时数超过 24 小时而不换行到天数,最好不要使用日期:

app.filter('secondsToTime', function() {函数 padTime(t) {返回 t <10 ?"0"+t : t;}返回函数(_秒){if (typeof _seconds !== "number" || _seconds <0)返回00:00:00";var hours = Math.floor(_seconds/3600),分钟 = Math.floor((_seconds % 3600)/60),秒 = Math.floor(_seconds % 60);return padTime(hours) + ":" + padTime(minutes) + ":" + padTime(seconds);};});

{{秒 |secondsToTime}}</b>

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

and

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


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

and

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

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

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