Angular.js:秒制时间架构过滤器 [英] Angular.js: Seconds to time schema filter

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

问题描述

我正在使用Angular.js,我有一个表示秒数的数字字符串(例如:610).

I'm using Angular.js, I have a string of number that represents seconds count (for example: 610).

我需要一个过滤器,将其转换为时间模式:10:10(10分钟10秒= 610秒).

I need a filter that will convert it to a time schema: 10:10 (10 minutes and 10 seconds = 610 seconds).

我应该怎么做?

推荐答案

manzapanza的答案仅在秒数小于86400(1天)时有效.日期对象必须完全为零.另外,最好返回实际的date对象,以使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,而又不缩短至几天,则最好不要使用日期:


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:秒制时间架构过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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