0

I need to manipulate each $firebasearray element to convert a date field ( saved as strings 'YYYYMMDD' ) in dates to expose then on the view at the corresponding tag :

<td width="7%"><input type="date" class="form-control"  ng-model="p.myDate"></td>

In this case the line above is inside an ng-repeat with the "p" elements from the array.I can't assign directly an string containing my date ( formated as 'YYYYMMDD' ) to the date field. It's necessary convert it to a date previously.

How ?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
GCoe
  • 849
  • 4
  • 14
  • 30
  • Firebase stores JSON data, and date values are not a known type there. See http://stackoverflow.com/questions/30021133/how-do-you-save-a-date-field-in-firebase-using-angularfire – Frank van Puffelen Mar 01 '16 at 21:06
  • I know that...this is why I'm saving dates as strings. – GCoe Mar 01 '16 at 21:09
  • The snippet above does not save it as a string. If you do the conversion somewhere, add that code too. See http://stackoverflow.com/help/mcve – Frank van Puffelen Mar 02 '16 at 07:03

1 Answers1

0

Add the moment.js library to your project. If the p.myDate is a date string, and you want a date object, try using this.

for(var i = 0; i < $scope.yourArray.length; i++) {
   if(moment($scope.yourArray[i].myDate).isValid()) {
     //if you want to keep the date string
     //$scope.yourArray[i].myDateString = $scope.yourArray[i].myDate;
     $scope.yourArray[i].myDate = new Date(moment($scope.yourArray[i].myDate));
   }
   else {
     console.log("not a valid date", $scope.yourArray[i].myDate);
   }
}

If there are no spaces, / or - between YYYY, MM and DD you should reformat the string. Let me know if this is the case and you need help with that.

pyromancer2
  • 173
  • 1
  • 1
  • 6
  • Hi, interesting approach. The conversion was ok and the date at the array was correctly converted from 'YYYYMMDD' to 'dd/MM/YYYY' but the INPUT expects a date object and then I have this error : angular.js:12520 Error: [ngModel:datefmt] Expected `03/01/2016` to be a date ... – GCoe Mar 01 '16 at 21:55
  • try replacing $scope.yourArray[i].myDate = moment($scope.yourArray[i].myDate); with $scope.yourArray[i].myDate = new Date(moment($scope.yourArray[i].myDate)); – pyromancer2 Mar 02 '16 at 02:22