Search code examples
angularjsmomentjscountdown

Incorrect day format returned from momentJS countdown


I used this simple script from: https://github.com/icambron/moment-countdown to make a simple countdown. The code below i'm using.

Used Code:

$interval(function(){

    $scope.nextDate = moment().countdown($scope.nextDateGet,
        countdown.DAYS|countdown.HOURS|countdown.MINUTES|countdown.SECONDS
    );

    $scope.daysCountdown = moment($scope.nextDate).format('dd');
    $scope.hoursCountdown = moment($scope.nextDate).format('hh');
    $scope.minutesCountdown = moment($scope.nextDate).format('mm');
    $scope.secondsCountdown = moment($scope.nextDate).format('ss');

},1000,0);

This gives correct output

$scope.nextDate.toString();

But this contains one string with the remaining days,hours,minutes and seconds. So i decided i want to split this string into 4 strings by using this:

$scope.daysCountdown = moment($scope.nextDate).format('dd');
$scope.hoursCountdown = moment($scope.nextDate).format('hh');
$scope.minutesCountdown = moment($scope.nextDate).format('mm');
$scope.secondsCountdown = moment($scope.nextDate).format('ss');

Example for input

2016-10-15 10:00:00 // $scope.nextDateGet

Desired output is something like this:

0 // (days)
12 // (hours)
24 // (minutes)
30 // (seconds)

But i can't seem to format the remainings days, i get this output:

Fr // Shortcode for the day the item is scheduled => I need the remaining days in this case that would be 0. The other formatting is correct.

Solution

  • The following output was correct if remaining days was not 0:

    $scope.daysCountdown = moment($scope.nextDate).format('D'); 
    

    If remaining days was 0 it would set remaining days on 14 so this work around did the trick:

    if(moment($scope.nextDate).isSame(moment(), 'day')){
        $scope.daysCountdown = 0;
    } else {
        $scope.daysCountdown = moment($scope.nextDate).format('D');
    }
    

    Any suggestions to improve this code are always welcome.