日期转换为天,小时,分钟格式

时间:2013-08-13 15:24:56

标签: javascript jquery regex

我正在将javascript中两个日期之间的差异转换为Days:Hours:Mins格式。

<html>
    <head>
<script type="text/javascript"
src="jquery-1.9.1.min.js""></script>
<script type="text/javascript">

    $(document).ready(function(){
        var today = new Date();
        var before = new Date();
        before.setDate(today.getDate() - 3);
        var diff = today.getTime() - before.getTime();

        var diffMinutes = diff / (60 * 1000) % 60;
        var diffHours = diff / (60 * 60 * 1000) % 24;
        var diffDays = diff / (24 * 60 * 60 * 1000);

        $('#days')[0].innerHTML = diffDays;
        $('#hours')[0].innerHTML = diffHours;
        $('#minutes')[0].innerHTML = diffMinutes;
        setInterval(myfunc,60000);              

        function myfunc(){              
            if(diff > 0){
                diff = diff - 60000;
                diffMinutes = diff / (60 * 1000) % 60;
                diffHours = diff / (60 * 60 * 1000) % 24;
                diffDays = diff / (24 * 60 * 60 * 1000);

                $('#days')[0].innerHTML = Math.floor(diffDays);
                $('#hours')[0].innerHTML = Math.floor(diffHours);
                $('#minutes')[0].innerHTML = diffMinutes;
            }
        }       
    });

</script>
    </head>
<body>
    <div>
<table>
    <tr>
        <td>
            <label>Days:</label>
        </td>
        <td>
            <label id="days"></label>
        </td>
        <td>
            <label>Hours:</label>
        </td>
        <td>
            <label id="hours"></label>
        </td>
        <td>
            <label>Mintues:</label>
        </td>
        <td>
            <label id="minutes"></label>
        </td>           
    </tr>
    </table>
    </div>
</body>

当计算差异时,它将像天:2小时:4分钟:52

我想要的是,如果天或小时是一位数,我想在它们之前追加0。

如何做到这一点?是否可以使用正则表达式或数字格式?

1 个答案:

答案 0 :(得分:1)

您应该使用Moment.js。查看Difference部分。如果由于某种原因你无法使用库,你至少可以使用他们的源代码并获得自己的解决方案。