如何以毫秒格式获取当前日期和日期之间的剩余小时数?

时间:2015-12-07 08:31:00

标签: angularjs

我正在使用angularjs来显示jsonArray中的项目列表。我想计算剩余的小时数,所以我认为为了解决我需要用jsonArray中的日期减去当前日期,即 purchaseTime 。输出应该是这样的格式: 12小时

脚本

angular.module('myApp', []).controller('orderCtrl', function($scope, $filter) {
$scope.orders = ${orderList.raw()};
});

jsonArray项目

"purchaseTime": "1449576000000"

HTML

<div ng-app="myApp" ng-controller="orderCtrl">
<div class="divs" ng-repeat="order in orders| orderBy: '+purchaseTime'">
    <div>
        <ul>
            <li><p>{{$index + 1}}</p></li>
            <li><p>{{(Date.now() - order.purchaseTime) | date:"h"}}</p></li>
        </ul>
    </div>
</div>

我认为我没有得到合适的剩余时间。很感谢任何形式的帮助。谢谢!

2 个答案:

答案 0 :(得分:0)

使用Date对象:

var a = new Date(); // Now
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // 2010
var d = (b-a); // difference in milliseconds

您可以通过将毫秒除以1000并将数字四舍五入来获得秒数:

var seconds = Math.round((b-a)/1000);

然后你可以通过再次将秒数除以60得到分钟,然后将得分除以60,然后将得分除以24,等等。

您会注意到我为第二个Date对象提供了一些值。这些参数如下:

// new Date(year, month, day, hours, minutes, seconds, milliseconds)

除非您希望代表的日期是必需的,否则您不一定需要提供所有这些值。只需要monthyear,其余的都是可选的。

答案 1 :(得分:0)

您可以为此目的创建自定义指令:

<强>的Javascript

var app = angular.module("myApp", []);

app.controller("orderCtrl", function($scope) {
    $scope.orders = [{id:1,"purchaseTime": "1449651824588"},{id:2,"purchaseTime": "1449665002689"}];
});

app.directive("calcTime", function($compile) {
    var timeDifference;
    var currentDate;
    var deadLine;
    var diffDays;
    var diffHours;
    var diffMinutes;
    return {
        restrict: 'A',
      link: function (scope, element, attrs) {
        currentDate = new Date();
        deadLine = new Date(parseInt(attrs.calcTime)); // setting purchase time Date Object
        deadLine = new Date(deadLine.setDate(deadLine.getDate()+1)); // setting purchase time Date Object + 1 day
        timeDifference = (deadLine.getTime()) - (currentDate.getTime()); // deadline data minus current date
                var diffDays = Math.floor(timeDifference / (1000 * 60 * 60 * 24)); 
        var diffHours = Math.floor(timeDifference / (1000 * 60 * 60)); 
        var diffMinutes = Math.floor((timeDifference-(diffHours*(1000 * 60 * 60))) / (1000 * 60)); 

        element.html(diffDays + " days, " + diffHours + " hours and "+ diffMinutes +" minutes till DeadLine")
            }
    };  
})

<强> HTML

<div ng-app="myApp" ng-controller="orderCtrl">
<div class="divs" ng-repeat="order in orders| orderBy: '+purchaseTime'">
    <div>
        <ul>
            <li>Purchase Time: {{order.purchaseTime | date:'MM/dd/yyyy - hh:mm'}}<p calc-time="{{order.purchaseTime}}"></p></li>
        </ul>
    </div>
</div>

工作JSFIDDLE