Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get number of days between two dates in java? [duplicate]

Tags:

java

date

Possible Duplicate:
Calculating the Difference Between Two Java Date Instances

How do I get number of days between two dates in Java?

What's the best way? Here is what I got but it's not the best:

public static ConcurrentHashMap<String, String> getWorkingDaysMap(int year, 
    int month, int day){
        int totalworkingdays=0,noofdays=0;
        String nameofday = "";
        ConcurrentHashMap<String,String> workingDaysMap = 
            new ConcurrentHashMap<String,String>();
        Map<String,String> holyDayMap = new LinkedHashMap<String,String>();
        noofdays = findNoOfDays(year,month,day);

        for (int i = 1; i <= noofdays; i++) {
            Date date = (new GregorianCalendar(year,month - 1, i)).getTime();
            // year,month,day
            SimpleDateFormat f = new SimpleDateFormat("EEEE");
            nameofday = f.format(date);

            String daystr="";
            String monthstr="";

            if(i<10)daystr="0";
            if(month<10)monthstr="0";

            String formatedDate = daystr+i+"/"+monthstr+month+"/"+year;

            if(!(nameofday.equals("Saturday") || nameofday.equals("Sunday"))){
                workingDaysMap.put(formatedDate,formatedDate);
                totalworkingdays++;
            }
        }

        return workingDaysMap;
    }

public static int findNoOfDays(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month - 1, day);
        int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        return days;
    }
like image 624
Joe Avatar asked Jun 15 '12 06:06

Joe


1 Answers

I usually do something like this:

final long DAY_IN_MILLIS = 1000 * 60 * 60 * 24;

int diffInDays = (int) ((date1.getTime() - date2.getTime())/ DAY_IN_MILLIS );

No need for external lib, and easy enough


Update: Just saw you want the "Dates" between too, similar method applies:

//assume date1 < date2

List<Date> dateList = new LinkedList<Date>();
for (long t = date1.getTime(); t < date2.getTime() ; t += DAY_IN_MILLIS) {
  dateList.add(new Date(t));
}

Of course, using JODA time or other lib may make your life a bit easier, though I don't see the current way difficult to implement


Update: Important Note! this only works for timezone that has no daylight saving or similar adjustment, or your definition of "difference in days" actually means "difference in 24-hour unit"

like image 90
Adrian Shum Avatar answered Oct 26 '22 12:10

Adrian Shum