无法显示剩余日期

时间:2015-03-22 14:20:19

标签: java android date

我的程序将从数据库中获取数据并在Listview中显示。现在我从数据库中获取日期并将其与我当前的日期进行比较并计算剩余的一天。我成功获取了数据并在列表视图中显示,但我的剩余日期代码无效。任何帮助将不胜感激!

    List<HashMap<String,Object>> aList = newArrayList<HashMap<String,Object>>();
    for (int i = 0; i<records.size(); i++) {
        HashMap<String, Object> hm = new HashMap<String, Object>();
        hm.put("txt", records.get(i).getAssname());
        hm.put("txt2", records.get(i).getAssTime());

        String ez = records.get(i).getAssTime();
        Calendar today = Calendar.getInstance();

        //count the remain day
        try {
            SimpleDateFormat dd = new SimpleDateFormat("dd/M/yyyy");
            Date date1= dd.parse(ez);
            Date date2 = today.getTime();
            long diff = Math.abs(date1.getTime() - date2.getTime());
            long diffDays = diff / (24 * 60 * 60 * 1000);

            hm.put("txt3", String.valueOf(diffDays));

        } catch (Exception e1) {
        }
        aList.add(hm);
    }

    // Keys used in Hashmap
    String[] from = {"txt","txt2","txt3"};

    // Ids of views in listview_layout
    int[] to = { R.id.assigment_name,R.id.assigment_ATime, R.id.assigment_remain};

    // Instantiating an adapter to store each items
    // R.layout.listview_layout defines the layout of each item
    SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.view_assignment_entry, from, to);

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

您可以尝试更改

long diff = Math.abs(date1.getTime() - date2.getTime());
long diffDays = diff / (24 * 60 * 60 * 1000);

long diff = date1.getTime() - date2.getTime();
long diffDays  = Math.abs(TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));

答案 1 :(得分:0)

final long DAY_MILLIS =  24* 60 * 60*1000 ;  

int Days = (int) ((date_1.getTime() - date_2.getTime())/ DAY_MILLIS );  

或者您可以将Joda时间库用于Java。

Days d = Days.daysBetween(startDate, endDate);  
int days = d.getDays(); 

我希望它会帮助你......!