Vignesh Vino
Vignesh Vino

Reputation: 1238

How to find difference in dates

I have a directory structure which having folders with date as the folder names.

Directory

I want to delete all the folder except last two days date.In this case except today's folder and last two days.i.e., 23,22,21. Here I can't use joda-time to find the difference between dates.

Here is my code trying towards this.

DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal=Calendar.getInstance();
    cal.add(Calendar.DATE, -2);
    //java.util.Date date=new java.util.Date();
    System.out.println("the date is "+dateFormat.format(cal.getTime()));
    String direct="D:\\tempm\\Sample\\"+dateFormat.format(cal.getTime());
    File file=new File(direct);
/*  if(!file.exists())
    {
        file.mkdir();
        System.out.println("folder created");
    }*/
  String path="D:\\tempm\\Sample\\";
    File file2=new File(path);
    for(File fi:file2.listFiles())
    {
        if(!fi.getAbsolutePath().equals(direct))
        {
            System.out.println(fi.getAbsolutePath());
            FileDeleteStrategy.FORCE.delete(fi);
            System.out.println("files except todays date were deleted");
        }
    } 

How to find difference of dates with this format?Also how to subtract that as a path for my case ?Any Ideas would be more helpful

thanks

Upvotes: 2

Views: 223

Answers (2)

No Idea For Name
No Idea For Name

Reputation: 11607

here

Date d1 = null;
Date d2 = null;
    try {
        d1 = Date.getInstance();
        d2 = format.parse(file2.getName());
    } catch (ParseException e) {
        e.printStackTrace();
    }    

    long diff = d2.getTime() - d1.getTime();
    long diffDays = diff / (60 * 60 * 1000 * 24);
    if(diffDays<=-3)
    {
        // Your code of delete
    }

now all you need is using the name of the folders to get the date, and use the Date's instance for the other side of the difference

Upvotes: 2

Veera
Veera

Reputation: 1815

This code will return difference between two dates.

/** Using Calendar - THE CORRECT WAY**/  
//assert: startDate must be before endDate  

public static long daysBetween(Calendar startDate, Calendar endDate) {  
  Calendar date = (Calendar) startDate.clone();  
  long daysBetween = 0;  
  while (date.before(endDate)) {  
    date.add(Calendar.DAY_OF_MONTH, 1);  
    daysBetween++;  
  }  
  return daysBetween;  
}  
}  

Upvotes: 2

Related Questions