Here you can find the source of diffDays(Calendar startDate, Calendar endDate)
Parameter | Description |
---|---|
startDate | a start date. |
endDate | an end date. |
public static long diffDays(Calendar startDate, Calendar endDate)
//package com.java2s; /*//from ww w.j a v a 2 s.c o m * Copyright (c) 2015-2016 QuartzDesk.com. * Licensed under the MIT license (https://opensource.org/licenses/MIT). */ import java.util.Calendar; public class Main { /** * Returns the number of days between the specified start date and end date. * If the end date precedes the start date, then this method returns 0. * Inspired by the <a href="http://tripoverit.blogspot.com/2007/07/java-calculate-difference-between-two.html"> * Java - calculate the difference between two dates</a> article. * * @param startDate a start date. * @param endDate an end date. * @return the number of days between the specified start date and end date. */ public static long diffDays(Calendar startDate, Calendar endDate) { Calendar sDate = (Calendar) startDate.clone(); long daysBetween = 0; int y1 = sDate.get(Calendar.YEAR); int y2 = endDate.get(Calendar.YEAR); int m1 = sDate.get(Calendar.MONTH); int m2 = endDate.get(Calendar.MONTH); //**year optimization** while (((y2 - y1) * 12 + (m2 - m1)) > 12) { //move to Jan 01 if (sDate.get(Calendar.MONTH) == Calendar.JANUARY && sDate.get(Calendar.DAY_OF_MONTH) == sDate.getActualMinimum(Calendar.DAY_OF_MONTH)) { daysBetween += sDate.getActualMaximum(Calendar.DAY_OF_YEAR); sDate.add(Calendar.YEAR, 1); } else { int diff = 1 + sDate.getActualMaximum(Calendar.DAY_OF_YEAR) - sDate.get(Calendar.DAY_OF_YEAR); sDate.add(Calendar.DAY_OF_YEAR, diff); daysBetween += diff; } y1 = sDate.get(Calendar.YEAR); } //** optimize for month ** //while the difference is more than a month, add a month to start month while ((m2 - m1) % 12 > 1) { daysBetween += sDate.getActualMaximum(Calendar.DAY_OF_MONTH); sDate.add(Calendar.MONTH, 1); m1 = sDate.get(Calendar.MONTH); } // process remainder date while (sDate.before(endDate)) { sDate.add(Calendar.DAY_OF_MONTH, 1); daysBetween++; } return daysBetween; } }