How do you save a DATE field in Firebase using Ang

2019-01-07 23:50发布

问题:

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?

回答1:

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(), 


回答2:

I just wanted to throw out a possibly more robust solution that may be useful to those who care about timezones.

I believe a valid solution is to store your dates as ISO-8601 formatted strings. If you read the linked Wikipedia article, you will see that "The lexicographical order of the representation thus corresponds to chronological order, except for date representations involving negative years."

The Firebase docs state that 'Strings [...] are sorted lexicographically in ascending order.', so as long as you're dealing with positive years, you will be able to do advanced time searches while maintaining timezone info.