How to save a DATE field in Firebase using AngularFire

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 click event

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

The following date is displayed on the console.

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

Here is 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 not saved in Firebase, the rest of the data is saved properly. What am I missing?

+6
source share
2 answers

You, unfortunately, have not included the code that initializes the OpenDate property. But it looks like you're trying to write a JavaScript Date object in Firebase. The Firebase documentation indicates that it supports these types:

object, array, string, number, boolean or null

To save the Date value, you will need to convert it to a supported type. For instance.

 $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(), 
+22
source

I just wanted to throw away a possibly more reliable solution that might be useful for those interested in time zones.

I believe the right solution is to store your dates as ISO-8601 formatted strings. If you read the related Wikipedia article, you will see that "the lexicographic order of the presentation is in chronological order, with the exception of ideas about dates with negative years."

Firebase docs state that 'Lines [...] are sorted lexicographically in ascending order.' , so while you are dealing with positive years, you can perform an advanced time search, saving time zone information.

+13
source

Source: https://habr.com/ru/post/986464/


All Articles