首页 > 解决方案 > 无法比较日期

问题描述

我正在从 JSON 中获取某些数据。我有一个日期("PaymentDueDateFormatted"),需要与当前日期进行比较并在列表视图中显示数据。但我无法确定这一点。这显示零数据。

我得到了日期,例如:"22-Dec-2017"。是否要转换成毫来比较?

ArrayList<String[]> invoiceListData1 = new ArrayList<>();
    for(int i = 0; i<invoices.length();i++){
    JSONObject jsonObject1 = invoices.getJSONObject(i);
    String date1 = jsonObject1.getString("PaymentDueDateFormatted");
    Calendar currentDate = Calendar.getInstance();
    if (currentDate.after(date1)) {
        String[] data = new String[9];
        data[0] = jsonObject1.getString("ID");
        data[1] = jsonObject1.getString("InvoiceNo");
        switch (getIntent().getExtras().getInt(Common.CUSTOMER_OR_SUPPLIER)) {
            case Common.CUSTOMER:
                data[2] = jsonObject1.getJSONObject("customerObj").getString("ID");
                data[3] = jsonObject1.getJSONObject("customerObj").getString("ContactPerson");
                data[7] = jsonObject1.getJSONObject("companiesObj").getString("Name");
                break;
            case Common.SUPPLIER:
                data[2] = jsonObject1.getJSONObject("suppliersObj").getString("ID");
                data[3] = jsonObject1.getJSONObject("suppliersObj").getString("ContactPerson");
                data[7] = jsonObject1.getJSONObject("companiesObj").getString("Name");
                break;
        }
        data[4] = jsonObject1.getString("PaymentDueDateFormatted");
        data[5] = jsonObject1.getString("BalanceDue");
        data[6] = jsonObject1.getString("PaidAmount");
        data[8] = jsonObject1.getString("DueDays");
        invoiceListData1.add(data);

        CustomAdapter adapter = new CustomAdapter(Invoices.this, invoiceListData1, (getIntent().getExtras().getInt(Common.CUSTOMER_OR_SUPPLIER) == Common.CUSTOMER ? Common.SALESLIST : Common.PURCHASELIST));
        invoiceList.setAdapter(adapter);
        (findViewById(R.id.list_card)).setVisibility(View.VISIBLE);
    }
}

标签: android

解决方案


试着打印你的currentdate,你就会明白为什么两个日期不相等。

不要在当前日期转换为毫秒 bcoz 包括小时、分钟和秒等时间

 Calendar currentDate = Calendar.getInstance();

这将使您有时间包含所有内容(秒、分钟、小时等),因此它永远不会与您从响应中获得的字符串相同

尝试这个

Date date = new Date();
String todayDate = new SimpleDateFormat("dd-MMM-yyyy").format(date);

而不是这个

 Calendar currentDate = Calendar.getInstance();

并与您的字符串日期进行比较


推荐阅读