Вывод данных за определенный промежуток времени
Есть список файлов которые создаются по текущей дате и времени. Мне нужно вывести не все файлы а только за последний 3 дня. Как можно это сделать ?
Код вывода всех файлов:
listViewArchive = findViewById(R.id.listViewArchive);
File[] filelist = dir.listFiles();
String[] theNamesOfFiles = new String[filelist.length];
for (int i = 0; i < theNamesOfFiles.length; i++) {
theNamesOfFiles[i] = filelist[i].getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, theNamesOfFiles);
listViewArchive.setAdapter(adapter);
Я в этом новичке, можно развернутым ответом.
Ответы (2 шт):
Например можно использовать BasicFileAttributes:
Path file = ...
BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
и там есть такой атрибут:
public abstract FileTime creationTime ()
Returns the creation time. The creation time is the time that the file was created.
If the file system implementation does not support a time stamp to indicate the time when the file was created then this method returns an implementation specific default value, typically the last-modified-time or a FileTime representing the epoch (1970-01-01T00:00:00Z).
Ещё есть такой вопрос на enSO. Чтобы получить дату именно из имени файла нужно конвертировать имя в дату:
String sDate1="31/12/1998";
Date date1=new SimpleDateFormat("dd/MM/yyyy").parse(sDate1);
System.out.println(sDate1+"\t"+date1);
где sDate1 это имя вашего файла, а dd/MM/yyyy это формат даты/времени в имени. И дальше задайте границы для фильтрации и сравнивайте дату из имени с ними (пример)
Как не странно это сработало и выводит всё корректно
ArrayList<String> theNamesOfFiles = new ArrayList<>();
File[] filelist = dir.listFiles();
for (int i = 0; i < filelist.length; i++) {
long diff = (new Date().getTime() - filelist[i].lastModified()) / 144 / 144 / 144;
Arrays.sort(filelist, Comparator.comparingLong(File::lastModified).reversed());
if (diff < 72)
theNamesOfFiles.add(filelist[i].getName());
}
Но я не совсем понимаю что значить / 144 / 144 / 144, если найдется человек который мне подробно расскажет. Буду очень благодарен
