Data output over a period of time

Viewed 95

There is a list of files that are created by the current date and time. I do not need to display all files, but only for the last 3 days. How can this be done?

Screen shot of list of files

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);

I am in this newbie, you can have a detailed answer.

3 Answers

Parse your inputs as a LocalDateTime.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMdd HHmmss" ) ;
LocalDateTime ldtFile = LocalDateTime.parse( fileName , f ) ;

Compare to the current date time as seen your specific time zone.

ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdtNow = ZonedDateTime.now( z ) ;

Get three days ago.

LocalDateTime ldtThreeDaysAgo = zdtNow.minusDays( 3 ).toLocalDateTime() ;  // Omits the context of a time zone, leaving only the date and time-of-day.

Compare each file's date-time.

if( ldtFile.isAfter( ldtThreeDaysAgo ) ) 
{
    … process 
}

All this has been covered many times on Stack Overflow. Search to learn more.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Maybe you could try something like this.

ArrayList<String> theNameOfFiles = new ArrayList<>();
for (int i = 0; i < filelist.length; i++) {
  long diff = (new Date().getTime() - filelist[i].lastModified()) / 1000 / 60 / 60 / 24;

  if (diff <= 3)
    theNamesOfFiles.add(filelist[i].getName());
}

To check if the creation date of a File is between two dates you need to extract the creationDate. You can do that as follow:

      Path path = file.toPath();
      BasicFileAttributes attributes = Files.readAttributes(path, BasicFileAttributes.class);
      long creationTimeMs = attributes.creationTime().to(TimeUnit.MILLISECONDS);
      // Do what you need to do with the creationTime
Related