If I have a vector containing a number of unsorted files, how can I categorize them by their last modified date?
what I need to do is to place the files into 3 other vectors, with the last modified date of “Today”, “Yesterday”, and “This Week”.
Vector<File> files; //This vector contains all the files that need to be categorized
Vector<File> todayFiles; //Empty
Vector<File> yesterdayFiles; //Empty
Vector<File> weekFiles; //Empty
I know I can use file.lastModified() to get the date, but it returns the date in milliseconds formatted as a long int, so I am not sure if there is an easier way to compare and group the dates without doing some intricate arithmetic work.
I am new to Java, so I have no idea how to approach this question, any help would be appreciated.
UPDATE
I was able to get the code to work somehow, but it is still not working properly. This is what I have:
private Calendar cal;
private long todayTime;
this.cal = Calendar.getInstance();
this.cal.set(Calendar.HOUR_OF_DAY, 0);
this.cal.set(Calendar.HOUR, 0);
this.cal.set(Calendar.MINUTE, 0);
this.cal.set(Calendar.SECOND, 0);
this.cal.set(Calendar.MILLISECOND, 0);
this.todayTime = cal.getTimeInMillis();
Now when I try to add them into the vector that I created, it is only grabbing files that have been modified in the PM of today’s date:
for(int i = 0; i < this.files.size(); i++) {
if(this.files.get(i).lastModified() >= this.todayTime) {
this.today.add(this.files.get(i));
}
}
Is there anything that I am doing wrong? Thank you for all the great responses by the way!
You can use the
Calendarclass to get timestamps for the required dates such as today and yesterday. For example, to get today’s (midnight) timestamp:Then you can compare this timestamp with
file.lastModified()and put the file into the corresponding vector.