【问题标题】:Order list of dates in String format字符串格式的日期顺序列表
【发布时间】:2013-12-15 15:51:30
【问题描述】:

我有一个包含 x 条日期记录的列表。问题是我所有的日期都是字符串格式,并且是数据库中的字符串。 我真的很想按日期订购我的列表(以字符串格式),但我真的不知道如何做到这一点。

废话不多说,这是我的列表,是自定义列表。

List<Finance> finances;

该列表包含以下字段:

public class Finance {
    private int id;
    private int categoryId;
    private int limitId;
    private double amount;
    private String date;
    private String description;
    }

这是我拥有的日期格式(在字符串中): 16/10/2013 2013 年 15 月 12 日 2013 年 11 月 15 日 2013 年 14 月 9 日

如何按日期对这个自定义列表进行排序?我已经看到了很多关于 Collections.sort 的示例,但由于我的自定义列表类型,我无法使用它。 我也看过一些 Comparable 的例子,但我并没有真正理解那些..

有人能告诉我,按照雾列表的日期实现长期排序的最佳方法是什么? 我还想要最轻量级的方法,尽可能少地使用资源。

编辑:我仍然没有找到可行的解决方案(19/12),仍然希望在这里得到回应..

谢谢 延特

【问题讨论】:

  • 你的日期格式是什么?
  • 一些记录的例子:16/10/2013 15/12/2013 14/9/2013 所以天/月/年
  • 同时使用:Comparator 用于按日期比较两个 Finance 对象。并使用此Comparator 将您的List&lt;Finance&gt;Collections.sort(List, Comparator) 排序。
  • @FabianBarney 你能给我写一个小例子吗?而且我似乎已经看到了一个问题。我将无法使用 Collections.Sort,因为我的列表是自定义类型。那么我该如何解决呢?
  • 您的自定义列表应该实现java.util.List。然后,您可以将所有这些方法与您的自定义列表类型一起使用。告诉我你尝试了什么,我也会发布一些代码。但我没有看到您甚至尝试为 Finance 对象编写 Comparator。

标签: android arrays list comparable


【解决方案1】:

好的,因为那里没有好的答案,几乎没有任何回应,我决定深入研究它,直到我修复它。

解决此问题的“最简单”方法是将所有日期以 yyyy-mm-dd 格式插入数据库。对于这部分的一个很好的解释,你应该看这里:https://stackoverflow.com/a/5733535/2262409

当您将日期放入 yyyy-mm-dd 并在 SQLite 中按日期排序时,日期将被正确排序。当您将它们放在 dd-mm-yyyy 中时,它们的排序将不正确。

长答案短: 在 SQL 部分解决了它。我以 yyyy-mm-dd 格式插入记录我得到它们

String selectQuery = "SELECT  * FROM Finance ORDER BY date desc";

然后我在用户看到它之前将它们重新格式化为 dd-mm-yyyy。示例:

String date = String.valueOf(values.get(position).getDate());

// we will format yyyy-mm-dd to dd-mm-yyyy for readability.
//the sql has ordered our dates correctly already.
String firstPartDate = date.substring(8, 10);
String secondPartDate = "/" + date.substring(5,7);
String thirdPartDate = "/" + date.substring(0,4);
String fullCorrectDate = firstPartDate + secondPartDate + thirdPartDate;
Log.i("firstpart", firstPartDate + secondPartDate + thirdPartDate);

dateFinance.setText(fullCorrectDate);

【讨论】:

    猜你喜欢
    • 2019-10-06
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多