Javascript秒数格式化成字符(如"剩余xx天xx小时xx分钟xx秒")

自定义函数

function formatSecond(second) {
            var d=0,h=0,m=0;
            if(second>86400){
                d=Math.floor(second/86400);
                second=second%86400;
            }
            if(second>3600){
                h=Math.floor(second/3600);
                second=second%3600;
            }
            if(second>60){
                m=Math.floor(second/60);
                second=second%60;
            }
            var result=second+'秒';
            if(m>0||h>0||d>0){
                result=m+'分'+result;
            }
            if(h>0||d>0){
                result=h+'小时'+result;
            }
            if(d>0){
                result=d+'天'+result;
            }
            return result;
        }

定义成angular的filter过滤器

var app=angular.module('myApp', ['ngRoute']);
app
.filter(  
    'formatSecond', function () {  
        return function (second) {
            var d=0,h=0,m=0;
            if(second>86400){
                d=Math.floor(second/86400);
                second=second%86400;
            }
            if(second>3600){
                h=Math.floor(second/3600);
                second=second%3600;
            }
            if(second>60){
                m=Math.floor(second/60);
                second=second%60;
            }
            var result=second+'秒';
            if(m>0||h>0||d>0){
                result=m+'分'+result;
            }
            if(h>0||d>0){
                result=h+'小时'+result;
            }
            if(d>0){
                result=d+'天'+result;
            }
            return result;
        }
    }
 );

 

转载于:https://my.oschina.net/u/1172593/blog/733025

你可能感兴趣的:(javascript)