Comparing 2 dates javafx

1.2k views Asked by At

I'm writing an application which is based on javafx/hibernate. Now i have problem when i want to make new table with articles that are sold last 7/30/365 days (or custom date chosen).

  • articles are stored in database with current date (Date articleDate = new Date(); )
  • all articles are fetched from database when the program is started and they are in an ObserveList named articlesDBList.

What i have tried so far:

ObserveList<ArticlesDB> sortForSevenDays =FXCollections.observableArrayList(); 
for(ArticleDB article: articleDBList) {
    if() { //missing statement for comparing articles by date for past 7 days
        sortForSevenDays.add(article);
    }
}  
1

There are 1 answers

0
ceekay On BEST ANSWER

On mkyong there are 3 possibilities in comparing Date in Java. In the comment section even the better choice (IF Javaversion < 8) of Joda-Time is presented.

The simpliest Solution without Joda would probably be just to compare using Calendar:

Calendar articleCal = Calendar.getInstance();
articleCal.setTime(articleDate);
//check for past 7 days
Calendar check = Calendar.getInstance();
check.add(Calendar.DATE, -7);
if(articleCal.after(check)) 
    sortForSevenDays.add(article);

INFO: Just keep in mind, that this compares for exactly 7 days (incl. minutes etc.).