Toxicable Toxicable - 7 months ago 14
Javascript Question

moment.js returning invaild date for every entry except the first when used on a angular 1.5 filter

So I decided to make a simple moment filter for formatting my times however I have an issue where the first input from a

ng-repeat
list will go through it correct but all the rest return invaild, yet when i manually enter the same line in through the console with the same input I get a correct output.

Here's the input

App.filter('momentFilter', function () {
return function (dateString, format, isUtc) {
console.log(dateString);
if (isUtc) {
var result = moment.utc(dateString).local().format(format);
console.log(result );
return result;
}
var result = moment(dateString).format(format);
console.log(result );
return result ;
};
});


my ng-repeat loop

<div ng-repeat="rank in rankings">
<div flex="15">
<label>Start Time: </label> {{rank.startTime | momentFilter:'D-MM':true}}
</div>
</div>


and a picture of the data/result with my manual input of the second item at the bottom showing that it's correct

enter image description here

Answer

If you send dateString like 1460028524737 as a string then you should convert it string to integer first. then will be working fine.

var dateValue = parseInt(dateString);
var result = moment.utc(dateValue).local().format(format);

and you should use else in your function otherwise always execute moment(dateString).format(format) and get that result, or use before if (isUtc) condition

return function (dateString, format, isUtc) {
    console.log(dateString);
    var dateValue = parseInt(dateString);
    if (isUtc) {
       var result = moment.utc(dateValue).local().format(format);
       console.log(result );
       return result;
    } else {
       var result = moment(dateValue).format(format);
       console.log(result );
       return result ;
    }
};
Comments