Maniraj Murugan
Maniraj Murugan

Reputation: 9084

Conversion of millisecond to hours format

I have a start date, time and end date, time and also i am finding out the total duration of travel. The output is in millisecond and i need to convert this into hours format. By searching other answers here i tried the following but no result.

<md-cell *mdCellDef="let row"> {{row?.duration | formatDuration}} </md-cell>

And ts file:

  export class StoppageComponent implements OnInit {

  constructor() {
  }

  ngOnInit() {
  }


      filter('formatDuration', function () {
        return function (input) {
            var totalHours, totalMinutes, totalSeconds, hours, minutes, seconds, result='';

            totalSeconds = input / 1000;
            totalMinutes = totalSeconds / 60;
            totalHours = totalMinutes / 60;

            seconds = Math.floor(totalSeconds) % 60;
            minutes = Math.floor(totalMinutes) % 60;
            hours = Math.floor(totalHours) % 60;

            if (hours !== 0) {
                result += hours+':';

                if (minutes.toString().length == 1) {
                    minutes = '0'+minutes;
                }
            }

            result += minutes+':';

            if (seconds.toString().length == 1) {
                seconds = '0'+seconds;
            }

            result += seconds;

            return result;
        };
      });
    }

I think the error is with ts file, as i am new in angular.

Is there is any direct conversion using pipe without using functions?

Upvotes: 1

Views: 2561

Answers (4)

Raja Mohamed
Raja Mohamed

Reputation: 1026

you can use this code directly

export class StoppageComponent implements OnInit {

constructor() {
 }

ngOnInit() {
}


filter('formatDuration', function () {
    return function (input) {
        var result = new Date(input);
var n = (d.getDate().toString()) +'/'+ (d.getMonth().toString())+'/' +(d.getFullYear().toString()) + '  '+ (d.getHours().toString()) +':'+ (d.getHours().toString()) +':'+ (d.getSeconds().toString());

        return result;
    };
  });
}

Upvotes: 0

Maniraj Murugan
Maniraj Murugan

Reputation: 9084

Other answers looks complicated, finally found out a solution myself..

Html as,

<md-cell *mdCellDef="let row"> {{getFormathours(row?.duration)}} </md-cell>

And ts,

getFormathours(input) {
    var totalHours, totalMinutes, totalSeconds, hours, minutes, seconds, result='';
    totalSeconds = input / 1000;
    totalMinutes = totalSeconds / 60;
    totalHours = totalMinutes / 60;

    seconds = Math.floor(totalSeconds) % 60;
    minutes = Math.floor(totalMinutes) % 60;
    hours = Math.floor(totalHours) % 60;

    console.log (hours + ' : '  + minutes + ' : ' + seconds);
    if (hours !== 0) {
        result += hours+' hr:';

        if (minutes.toString().length == 1) {
            minutes = '0'+minutes;
        }
    }

    result += minutes+' min';

      if (seconds.toString().length == 1) {
          seconds = '0'+seconds;
      }

      result += seconds;

    return result;
}

This gives the exact output that i needed and much more clear solution based on my question.. Anyhow i appreciate others answers too for your effort.

Upvotes: 4

Pako Navarro
Pako Navarro

Reputation: 168

For me, the best choice (without errors) is use the moment library, instead Date. Please check https://momentjs.com/docs/

var t1 = moment('2017/10/5 15:23');
var t2 = moment('2017/10/5 15:23');

var differenceMinutes = t1.diff(t2, 'minutes');
var differenceMilliseconds = t1.diff(t2, 'minutes');

Using popular and tested libraries, could be better. You can use in angular templates:

https://github.com/urish/angular2-moment

Example:

{{startDate | amDifference: endDate :'' }}

Upvotes: 0

Rajesh
Rajesh

Reputation: 24915

You do not need to reinvent the wheel. You can use Date objects to get duration.

Assuming you have 2 date objects,

  • Get the difference between them. Since you already have millseconds, you already have completed this step.
  • Now create a new date object and remove time value.
  • Now when you set new time value(difference) to it, you have all the values. Just use the function and get the values and display in your format.

function getTravelDuration(date1, date2) {
  var diff = +date2 - +date1;
  var today = new Date();
  today.setHours(0,0,0,0);
  var arrival = new Date(+today + diff);
  var duration = ['getFullYear', 'getMonth', 'getDate', 'getHours', 'getMinutes', 'getSeconds'].reduce(function(p,c,i,a){
    var value = arrival[c]() - today[c]();
    if(value) {
      p += value;
      p += ((c === 'getFullYear') ? ' Year' : c.replace('get', ' ')) + ' '
    }
    return p;
  }, '');
  console.log(duration);
}

function doubleDigits(str){
  return ('00' + str).slice(-2)
}

getTravelDuration(new Date(2017, 10, 5, 5), new Date(2017, 10, 5, 15, 23));
getTravelDuration(new Date(2017, 10, 5, 5), new Date(2017, 10, 6, 15, 23, 30));

Upvotes: 0

Related Questions