简体   繁体   English

如何计算饼图中显示的日期与当前日期之间的差异

[英]How to calculate the difference between the dates shown in the piechart with the current date

I have an SQLite database containing a number of tasks and the dates on which these tasks were completed.我有一个 SQLite 数据库,其中包含许多任务和完成这些任务的日期。 I am then adding these dates as PieEntries in a piechart.然后我将这些日期添加为饼图中的 PieEntries。 I would like to find the difference between the dates on the chart and the current date.我想找出图表上的日期和当前日期之间的差异。

The idea would be to set different colors to different segments of the chart depending on the difference between the dates.这个想法是根据日期之间的差异为图表的不同部分设置不同的颜色。

I've found a few posts on here such as this one that I've been using : Android difference between Two Dates .我在这里找到了一些帖子,例如我一直在使用的帖子: 两个日期之间的 Android 差异 But so far nothing seems to be working.但到目前为止,似乎没有任何效果。

Below is my cursor cycling through the database and using that to get the dates and place them in to PieEntry List.下面是我的光标在数据库中循环并使用它来获取日期并将它们放入 PieEntry 列表中。 There is also the code I'm using to calculate the current date and the code to calculate the difference between those that populate the chart and the current date.还有我用来计算当前日期的代码和用于计算填充图表和当前日期之间差异的代码。

final ArrayList<TaskObject> taskObjects = new ArrayList<>();

    if (mCursor != null) {
        mCursor.moveToFirst();
        do {
            TaskObject taskObject = new TaskObject();
            taskObject.setTask(mCursor.getString(mCursor.getColumnIndex(TaskEntry.COLUMN_TASK)));
            taskObject.setObserver(mCursor.getString(mCursor.getColumnIndex(TaskEntry.COLUMN_OBSERVER)));
            taskObject.setDate(mCursor.getString(mCursor.getColumnIndex(TaskEntry.COLUMN_DATE)));
            taskObjects.add(taskObject);
        } while (mCursor.moveToNext());

        float distribution = 100 / taskObjects.size();

        List<PieEntry> pieEntries = new ArrayList<>();
        for (int i = 0; i < taskObjects.size(); i++) {
            pieEntries.add(new PieEntry(distribution, (taskObjects.get(i).getTask()) + "\n" + taskObjects.get(i).getDate()));

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
            String pastDateString = taskObjects.get(i).getDate();
            Date currentDate = Calendar.getInstance().getTime();
            Date pastDate = null;
            try {
                pastDate = simpleDateFormat.parse(pastDateString);
            } catch (ParseException e) {
                e.printStackTrace();
            }

            //Comparing dates
            long difference = Math.abs(currentDate.getTime() - pastDate.getTime());
            long differenceDates = difference / (24 * 60 * 60 * 1000);

            //Convert long to String
            String dayDifference = Long.toString(differenceDates);

            Log.e("HERE","HERE: " + dayDifference);
        }

        PieDataSet pieDataSet = new PieDataSet(pieEntries, "Label");
        pieDataSet.setColors(ColorTemplate.MATERIAL_COLORS);
        PieData pieData = new PieData(pieDataSet);

        mPieChart.setData(pieData);
        mPieChart.invalidate();
    }
    mCursor.close();

The idea is to subtract the pastDate from the currentDate to reveal an integer value that could then be used to change the color of the piechart segment.这个想法是从 currentDate 中减去过去的日期以显示一个整数值,然后可以使用它来更改饼图段的颜色。

EDIT:编辑:

            List<PieEntry> pieEntries = new ArrayList<>();
            for (int i = 0; i < taskObjects.size(); i++) {
                pieEntries.add(new PieEntry(distribution, (taskObjects.get(i).getTask()) + "\n" + taskObjects.get(i).getDate()));

                mPieDataSet = new PieDataSet(pieEntries, "Versatility Matrix & Qualification Status");

                String pastDateString = taskObjects.get(i).getDate();
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
                Date d = null;
                try {
                    d = simpleDateFormat.parse(pastDateString);//catch exception
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                Calendar pastDate = Calendar.getInstance();
                pastDate.setTime(d);

                Calendar currentDate = Calendar.getInstance();

                long diff = currentDate.getTimeInMillis() - pastDate.getTimeInMillis();
                long days = diff/(24*60*60*1000);
                int daysDifference = (int) days;
                Log.d(TAG, "days in difference = " + daysDifference);


                if(daysDifference >= 90) {
                    mPieDataSet.setColor(Color.RED);
                } else if (daysDifference < 90 && daysDifference >= 60) {
                    mPieDataSet.setColor(Color.YELLOW);
                } else {
                    mPieDataSet.setColor(Color.GREEN);
                }
            }

            PieData pieData = new PieData(mPieDataSet);
            mPieChart.setData(pieData);
            mPieChart.invalidate();

This new code doesn't return an integer value for the difference in days and all chart segments are showing as red currently.此新代码不会返回天数差异的整数值,并且所有图表段当前都显示为红色。

It's a guess: When you do mPieDataSet.setColor(Color.RED);这是一个猜测:当你做mPieDataSet.setColor(Color.RED); , I think you are setting the colour on the entire pie, not just on the individual slice/pie entry. ,我认为您是在整个饼图上设置颜色,而不仅仅是在单个切片/饼图条目上。 In this way if the last entry you are processing in your loop is 90 days old, all of your pie chart gets the red colour.这样,如果您在循环中处理的最后一个条目是 90 天前的,那么您的所有饼图都会变为红色。

I have not been able to reproduce a wrong calculation in your code where the count of days would go over 90 when it shouldn't.我无法在您的代码中重现错误的计算,其中天数会超过 90,而本不应该。 If I set pastDateString to 4/1/2019 , I get 88 days, and your if / else construct chooses the YELLOW way through.如果我将pastDateString设置为4/1/2019 ,我得到 88 天,并且您的if / else构造选择黄色方式通过。

Disclaimer: I don't know MPAndroidChart.免责声明:我不知道 MPAndroidChart。

General recommendations一般建议

If your database has a date datatype, use it for dates.如果您的数据库具有date数据类型,请将其用于日期。 Don't store them as strings.不要将它们存储为字符串。 Second, consider not using SimpleDateFormat , Calendar and Date .其次,考虑不使用SimpleDateFormatCalendarDate They are poorly designed and long outdated.它们的设计很差,而且已经过时了。 You may add ThreeTenABP to your Android project and use LocalDate and other classes from java.time, the modern Java date and time API.您可以将 ThreeTenABP 添加到您的 Android 项目中,并使用LocalDate和来自 java.time(现代 Java 日期和时间 API)的其他类。 It is so much nicer to work with.和它一起工作要好得多。 And gives much better support for calculation of differences between dates:并为计算日期之间的差异提供更好的支持:

    long days = ChronoUnit.DAYS.between(pastLocalDate, LocalDate.now(yourTimeZone));

Links链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM