When comparing dates, put the objects that fall in the last week on the list

I am working on a project where the user adds a completion date when adding a book. I save it in an object called FinishedBooks with the completion date and other data of the book. I list these books in another activity. I have a filter button in the corner of the screen. This button will list the books that have been finished in the last week. I wrote a method for this before, here is my method:

private void lastWeekFilter(List<FinishedBooks> finishedBooks) {
    List<FinishedBooks> lastWeekList = new ArrayList<>();

    // take now time
    long currentTimeMillis = System.currentTimeMillis();

    // Calculate the time one week ago
    long oneWeekMillis = 7L * 24L * 60L * 60L * 1000L;
    long oneWeekAgoMillis = currentTimeMillis - oneWeekMillis;

    // Check each item in the list
    for (FinishedBooks book : finishedBooks) {
        long endDateMillis = book.endDate;

        System.out.println("End Date: " + endDateMillis);
        System.out.println("One Week Ago Millis: " + oneWeekAgoMillis);
        System.out.println("******************************");

        // If the due date falls within the last 1 week, add the item to the filteredList
        if (endDateMillis >= oneWeekAgoMillis && endDateMillis <= currentTimeMillis) {
            lastWeekList.add(book);
        }
    }
    finishedBooksAdapter.setLastWeekFilter(lastWeekList);
}

My code didn’t work as I wanted, it never enters the if block. So I used a System.out.println(); to see if the values meet the if conditions. Here’s my logcat output:

I/System.out: End Date: 1684159940
I/System.out: One Week Ago Millis: 1683740684856
I/System.out: ******************************
I/System.out: End Date: 1683987159
I/System.out: One Week Ago Millis: 1683740684856
I/System.out: ******************************

Although my incoming data meets the conditions, the object I want is not included in the list. It does not enter the if block. lastWeekList.size() returns 0.

I am grateful for your help in advance.

I was expecting the conditions to be met and these objects to be listed, but the list remains empty.

>Solution :

The date from the book -which is really a timestamp- doesn’t include milliseconds. Notice that the length has 3 less digits. Multiply it by 1000 to make it comparable to the other timestamp.

Leave a Reply