asax
asax

Reputation: 237

Countdown Timer in Angular using $Interval()

I am implementing a function to have a countdown in Angular form current time - existing time in future. If the time has elapsed then display a message. Timer ran out in ..... HH:MM:SS

The goal is to get a timer that is Current time - end time. Save it to a Variable TotalHours.

Then calculate the time remaining for NOW to total hours. For example TotalHours = 5. And NOW is 9/14/2016 1:16:00 PM then FinalCountDown = 6:16:00 PM. That is the timer I want running...

Here is how I am doing it...

if (info.endTime) {

  var CurrentTime = new Date().toLocaleString('en-US');
  moment.locale(); // en

  var TotalHours = moment.utc(moment(info.diffTime, "DD/MM/YYYY HH:mm:ss").diff(moment(CurrentTime, "DD/MM/YYYY HH:mm:ss"))).format("HH:mm:ss");

  info.finalCountDown= TotalHours;

};

The issue here is the following:

Case 1:

endTime = 9/15/2016 9:16:00 AM
currentTime = 9/15/2016 1:21:00 PM

TotalHours = 4:05:00

But... if its after next 2 days...

Case 2:

endTime = 9/17/2016 9:16:00 AM
currentTime = 9/15/2016 1:21:00 PM

TotalHours = 4:05:00

Total hours is still the same...

I need it to add 24hours + 24 hours + extra time = 48 + 4:05:00 = 52:05:00

also I want it to display as: 52h:05m:00s

Please let me know how to solve this...

Upvotes: 0

Views: 1614

Answers (1)

Hooligancat
Hooligancat

Reputation: 3788

A quick and dirty solution would be to simply convert the difference between the two date/time objects to milliseconds and then do some math on the milliseconds and format the output as follows:

var currentTime = new Date("9-15-2016 13:21:00");
var endTime = new Date("9-17-2016 09:16:00");

var ms = (endTime - currentTime); // ms of difference
var days = Math.round(ms/ 86400000);
var hrs = Math.round((ms% 86400000) / 3600000);
var mins = Math.round(((ms% 86400000) % 3600000) / 60000);

$scope.finalCountdown = (days + "d:" + hrs + " h:" + mins + "m left");

You could add in a calculation for the seconds if you needed and you can do some formatting of the numbers to have leading zeros.

However, doing this doesn't account for issues such as leap-years and other data and time anomalies. A better suggestion would be to use angular-moment which utilizes Moment.js as it can handle differences and formatting with ease.

Upvotes: 1

Related Questions