AngularJS - How do you convert milliseconds to xHours and yMins

前端 未结 9 926
小鲜肉
小鲜肉 2020-12-14 18:26

I\'ve a requirement where I want to convert milliseconds to xHours and yMins in AngularJS.

For ex. 3600000 should be displayed as 1h 0m.

I tried using

相关标签:
9条回答
  • 2020-12-14 18:57

    For TypeScript but could be adapted for any language.

    convertTimeMS(timeMS: number): string {
      const seconds = Math.floor(timeMS / 1000);
      const minutes = Math.floor(seconds / 60);
      const hours = Math.floor(minutes / 60);
    
      let str: string = '';
    
      if(hours > 0) {
        str = str + hours.toString() + 'h ';
      }
      if(minutes%60 > 0) {
        str = str + Number(minutes%60).toString() + 'm ';
      }
      if(seconds%60 > 0) {
        str = str + Number(seconds%60).toString() + 's ';
      }
    
      return str;
    }
    
    0 讨论(0)
  • 2020-12-14 19:02

    There is date converter in AngularJS, just set required date format:

    {{milliseconds | date:'yyyy-MM-dd HH:mm'}}
    

    Also I created such 'timeAgo' filter using jQuery timeago() function:

    .filter('timeAgo', function() {
        return function(input) {
            if (input == null) return "";
            return jQuery.timeago(input);
        };
    })
    

    Usage:

    {{milliseconds | timeAgo}}
    

    or use together both format for wide date representation:

    <span>{{milliseconds | timeAgo}}, {{milliseconds  | date:'yyyy-MM-dd HH:mm'}}</span>
    

    Result:

    12 minutes ago, 2015-03-04 11:38
    
    0 讨论(0)
  • 2020-12-14 19:08

    Try this one

    var app = angular.module ( 'myApp', [] ) ;
    app.controller ( 'myController', function ( $scope, $filter) {
        $scope.date = $filter('date')(milliseconds, 'MM/dd/yyyy');
    });
    
    0 讨论(0)
提交回复
热议问题