Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS - How do you convert milliseconds to xHours and yMins

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 date:'H:m' and date:'HH:mm' from the date formats on Angular's website.

But those give 19:0 and 19:00 instead of 1h 0m.

Any pointers of achieving this will be helpful.

Thanks

like image 517
Pritish Avatar asked Nov 25 '13 14:11

Pritish


People also ask

How do you convert milliseconds to time?

To convert a second measurement to a millisecond measurement, multiply the time by the conversion ratio. The time in milliseconds is equal to the seconds multiplied by 1,000.

How do you convert milliseconds to seconds in node JS?

floor((ms/1000/60) << 0), sec = Math. floor((ms/1000) % 60); console. log(min + ':' + sec);


2 Answers

Let make a custom filter for this, e.g:

.filter('millSecondsToTimeString', function() {
  return function(millseconds) {
    var oneSecond = 1000;
    var oneMinute = oneSecond * 60;
    var oneHour = oneMinute * 60;
    var oneDay = oneHour * 24;

    var seconds = Math.floor((millseconds % oneMinute) / oneSecond);
    var minutes = Math.floor((millseconds % oneHour) / oneMinute);
    var hours = Math.floor((millseconds % oneDay) / oneHour);
    var days = Math.floor(millseconds / oneDay);

    var timeString = '';
    if (days !== 0) {
        timeString += (days !== 1) ? (days + ' days ') : (days + ' day ');
    }
    if (hours !== 0) {
        timeString += (hours !== 1) ? (hours + ' hours ') : (hours + ' hour ');
    }
    if (minutes !== 0) {
        timeString += (minutes !== 1) ? (minutes + ' minutes ') : (minutes + ' minute ');
    }
    if (seconds !== 0 || millseconds < 1000) {
        timeString += (seconds !== 1) ? (seconds + ' seconds ') : (seconds + ' second ');
    }

    return timeString;
};
});

Then use it:

<div>{{ millSeconds | millSecondsToTimeString }}</div>
like image 178
haotang Avatar answered Sep 16 '22 21:09

haotang


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
like image 28
Dmitri Algazin Avatar answered Sep 17 '22 21:09

Dmitri Algazin