![](/img/trans.png)
[英]How to format decimal hours greater than 24 hours into hours minutes in JavaScript
[英]How format a time in hours greater than 24 hours AngularJS
我有一個以分鍾為單位的十進制值3361 ,需要轉換為小時並以以下格式顯示: 56 : 01 : 00
我嘗試了這段代碼:
$scope.myTime = new Date(1970, 0, 1).setMinutes(3361);
<input type="text" class="form-control" ng-model="myTime | date:'HH:mm:ss'">
但是結果卻不是我所期望的: 08 : 01 : 00
我擔心您無法使用角度date
過濾器來實現所需的功能。
您可以創建自定義過濾器(此處為官方角度指南 ),並以所需的格式生成結果。
例如,您可以使用moment.duration(3361, 'minutes');
創建時刻 moment.duration(3361, 'minutes');
然后使用moment-duration-format獲取HH:mm:ss
格式的持續時間。
這是一個完整的實時示例:
angular.module('MyApp', []) .filter('durationFormat', function() { return function(input) { input = input || ''; var out = ''; var dur = moment.duration(input, 'minutes'); return dur.format('HH:mm:ss'); }; }) .controller('AppCtrl', function($scope) { $scope.myTime = 3361; })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script> <div ng-app="MyApp" ng-controller="AppCtrl"> {{ myTime | durationFormat }} </div>
獲得相同輸出的另一種方法是使用角矩持續時間格式 ,該格式具有要使用的過濾器並顯示力矩持續時間。 您可以使用amdCreate
指定'minutes'
單位來創建持續時間,然后使用amdFormat
對其進行amdFormat
。
這里是一個例子:
angular.module('MyApp', ['angularDurationFormat']) .controller('AppCtrl', function($scope) { $scope.myTime = 3361; })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script> <script src="https://cdn.rawgit.com/vin-car/angular-moment-duration-format/0.1.0/angular-moment-duration-format.min.js"></script> <div ng-app="MyApp" ng-controller="AppCtrl"> {{ myTime | amdCreate:'minutes' | amdFormat:'HH:mm:ss' }} </div>
PS。 我是angular-moment-duration-format的創建者。
沒有內置的AngularJS日期/時間過濾器可以完成您要顯示的內容。
但是,您可以創建一個自定義AngularJS過濾器 ,該過濾器將實現您所需要的。
% 60
將為您節省時間。 然后,您可以簡單地將其減去60除以得到小時數。
function minutesToHours(min) { var minutes = min % 60; var hours = (min-minutes)/60; minutes = minutes < 10 ? '0' + minutes : minutes; return hours+':'+minutes+':00'; } console.log(minutesToHours(3361));
嘗試使用以下方法更改范圍,並在控制器中添加$ filter
$scope.myTime = $filter('date')(new Date(1970, 0, 1).setMinutes(3361), 'HH:mm:ss');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.