How do you save a DATE field in Firebase using AngularFire

Luis Cabrera picture Luis Cabrera · May 4, 2015 · Viewed 18.8k times · Source

I have a screen with a DATE field (Start Date) where the user can enter any date

<label class="item item-input">
     <span class="input-label">Start Date</span>
     <input type="date" ng-model="currentItem.OpenDate">
</label>

I added the following to the Save button's click event

console.log("Normal date " + $scope.currentItem.OpenDate);

The console shows the following date

Normal date Fri May 01 2015 00:00:00 GMT-0400 (Eastern Daylight Time)

Here's the push event

$scope.data.accounts.push({ 'AccountName': $scope.currentItem.AccountName, 'StartBalance': $scope.currentItem.StartBalance, 'OpenDate': $scope.currentItem.OpenDate, 'AccountType': $scope.currentItem.AccountType });

HOWEVER, the date $scope.currentItem.OpenDate is not getting saved to Firebase, the rest of the data is saving properly. What am I missing?

Answer

Frank van Puffelen picture Frank van Puffelen · May 4, 2015

You unfortunately didn't include the code that initializes the OpenDate property. But it looks like you're trying to write a JavaScript Date object into Firebase. The Firebase documentation specifies that it supports these types:

object, array, string, number, boolean, or null

In order to store the Date's value, you will have to convert it to a supported type. E.g.

$scope.data.accounts.push({ 
  'AccountName': $scope.currentItem.AccountName, 
  'StartBalance': $scope.currentItem.StartBalance, 
  'OpenDate': $scope.currentItem.OpenDate.toString(), 
  'AccountType': $scope.currentItem.AccountType 
});

Or alternatively:

  'OpenDate': $scope.currentItem.OpenDate.getTime(),