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
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.
floor((ms/1000/60) << 0), sec = Math. floor((ms/1000) % 60); console. log(min + ':' + sec);
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With