【问题标题】:Storing Date input values on Firebase在 Firebase 上存储日期输入值
【发布时间】:2017-04-11 07:00:21
【问题描述】:

这就是我的代码的样子

cropref.child(mycrop.name).push({
                          cropname:mycrop.name,
                          croplocation:mycrop.location,
                          cropplantdate:mycrop.plantdate.toString(),
                          cropharvestdate:mycrop.harvestdate.toString(),         
                  })

mycrop.harvestdatemycrop.plantdate 都是来自我的 html 的日期输入

<input type="date" ng-model='mycrop.harvestdate'>

<input type="date" ng-model='mycrop.harvestdate'>

为了能够将数据放到我的 Firebase 数据库中,我需要先将其转换为字符串

cropplantdate:mycrop.plantdate.toString(),      

但我的 Firebase 数据库中的数据包括时间和时区

样本数据

Sat Dec 12 2020 00:00:00 GMT+0800 (Malay Peninsula Standard Time)

所以一旦我从数据库中调用数据,我就无法过滤它,因为它不再是日期而是字符串。 我该如何解决这个问题,以便我可以过滤存储在我的数据库中的日期(转换为字符串)

【问题讨论】:

  • 如果您坚持将日期存储为字符串,请将它们存储为按字典顺序按时间顺序排列的格式。例如。 2016-11-27T17:01:19。但更好的是:只需将时间戳存储为自纪元以来的毫秒数。见stackoverflow.com/questions/34957249/…

标签: angularjs firebase firebase-realtime-database angular-filters


【解决方案1】:

两种选择

1) 以更通用但人类可读的格式存储日期,因此现在是 11 月 27 日星期日 09:13:38

20161127091338

2) 使用

将日期存储为 unix 时间戳(以毫秒为单位)
(new Date).getTime() / 1000

#2 有很多变体,因此请进行一些研究,看看哪种最适合您的用例。

您可以将任一答案保存为字符串,但 #1 会更容易搜索,因为查询不需要任何类型的转换 - 以查看今天的事件

queryStartingAt("20161127") and queryEndingAt("20161127")

【讨论】:

  • 我喜欢第一个,但是先生,我如何将它转换回日期格式?再次喜欢 mm/dd/yyyy
  • @Nevin 有很多方法可以转换日期,但请检查此问题并回答 Angular Date Converstion
【解决方案2】:

您需要先在格式中转换日期。您可以为此使用 SimpleDateFormatFormat。

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

现在您可以轻松地将日期格式化为这种格式

String mynewdate = sdf.format(mycrop.plantdate.getTime());

今天的输出是:

2016-11-27

当然,您可以将其反转回日历。我是这样做的:

 public static Calendar fromStringtoCalendar(String datestring){
    int year =  Integer.valueOf(datestring.substring(0, 4));
    int month =  Integer.valueOf(datestring.substring(5, 7)) -1;
    int day =  Integer.valueOf(datestring.substring(8, 10));
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month, day);
    return calendar;
}

【讨论】:

  • 我认为代码是用于 android 的?我正在使用网络顺便说一句
  • 哦,对不起,我弄错了。
猜你喜欢
  • 1970-01-01
  • 2018-07-29
  • 1970-01-01
  • 1970-01-01
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-16
相关资源
最近更新 更多