如何使用 AngularFire 在 Firebase 中保存 DATE 字段

How do you save a DATE field in Firebase using AngularFire

我有一个带有日期字段(开始日期)的屏幕,用户可以在其中输入任何日期

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

我将以下内容添加到“保存”按钮的点击事件中

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

控制台显示以下日期

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

这是推送事件

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

但是,日期 $scope.currentItem.OpenDate 没有保存到 Firebase,其余数据保存正确。我错过了什么?

很遗憾,您没有包含初始化 OpenDate 属性 的代码。但看起来您正在尝试将 JavaScript Date 对象写入 Firebase。 Firebase documentation 指定它支持这些类型:

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

为了存储 Date 的值,您必须将其转换为受支持的类型。例如

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

或者:

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

我只是想抛出一个可能对那些关心时区的人有用的更强大的解决方案。

我认为一个有效的解决方案是将您的日期存储为 ISO-8601 格式的字符串。如果您阅读链接的维基百科文章,您会看到 "The lexicographical order of the representation thus corresponds to chronological order, except for date representations involving negative years."

Firebase 文档指出 'Strings [...] are sorted lexicographically in ascending order.',因此只要您处理的是正年份,您就可以在维护时区信息的同时进行高级时间搜索。