如何按存储为值的日期对Firebase数据进行排序

时间:2018-01-17 13:38:48

标签: android firebase firebase-realtime-database

我正在尝试使用日期对存储在Firebase数据库中的数据进行排序。当前的存储结构是:

website-scraper

因此,通过使用Recyclerview,我只能按字母顺序排序获取数据。如何使用函数orderByValue使用日期对此数据进行排序?

如果有一个事件在02/05/18第一次在02/05/18和第三次在05/05/18有三个事件,我希望数据显示为最新的将在01/05/18然后在02/05/18然后在05/05/18。

我已经阅读了有关Stack Overflow的各种问题,但这些问题都没有帮助我解决问题。

2 个答案:

答案 0 :(得分:1)

您应该以不同的方式存储日期,因为您将很难以这种方式执行此操作(您必须在客户端中执行此操作)。相反,您应该将日期存储为时间戳,如下所示:

{
    date: 1514978640000,
    description: "Some Description"
    title: "Some Title"
}

同时,您可以在一个字段存储日期和时间,然后在您使用它的任何地方进行转换。排序变得微不足道。

答案 1 :(得分:1)

你应该以毫秒为单位存储数据,不是那么难,然后你可以带来数据并在Date中解析它,看看这个片段

   try{

         HttpClient httpclient = new DefaultHttpClient();
                        HttpResponse response = httpclient.execute(new HttpGet("https://google.com/"));
                        StatusLine statusLine = response.getStatusLine();
                        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                            DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH);
                            dateStr = response.getFirstHeader("Date").getValue();
                            Date startDate = df.parse(dateStr);
                            dateStr = String.valueOf(startDate.getTime() / 1000);

   } else {
                    //Closes the connection.
                    response.getEntity().getContent().close();
                    throw new IOException(statusLine.getReasonPhrase());
                }
            } catch (ClientProtocolException e) {
                Log.d("Response", e.getMessage());
            } catch (IOException e) {
                Log.d("Response", e.getMessage());
            } catch (ParseException e) {
                e.printStackTrace();
            }

在这里,您可以在Google中获得服务器时间(以毫秒为单位)

或者如果您想从手机中获取时间

Long tsLong = System.currentTimeMillis() / 1000;

您可以将这些毫秒转换为日期

 SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
            String myDate = formatter.format(new Date(Long.parseLong(HERE_YOUR_MILIS_DATE) * 1000L));

希望有所帮助

相关问题