Here you can find the source of getDifferenceInDays(final Date startDate, final Date endDate)
Parameter | Description |
---|---|
startDate | start date |
endDate | end date |
public static int getDifferenceInDays(final Date startDate, final Date endDate)
//package com.java2s; /*//from w ww . j av a 2 s. co m * jGnash, a personal finance application * Copyright (C) 2001-2015 Craig Cavanaugh * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Main { private static final long MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000; /** * ThreadLocal for a {@code GregorianCalendar} */ private static final ThreadLocal<GregorianCalendar> gregorianCalendarThreadLocal = new ThreadLocal<GregorianCalendar>() { @Override protected GregorianCalendar initialValue() { return new GregorianCalendar(); } }; /** * Determines the difference in days of two dates * * @param startDate start date * @param endDate end date * @return number of days */ public static int getDifferenceInDays(final Date startDate, final Date endDate) { final GregorianCalendar c = gregorianCalendarThreadLocal.get(); c.setTime(trimDate(startDate)); final long startMilli = c.getTimeInMillis() + c.getTimeZone().getOffset(c.getTimeInMillis()); c.setTime(trimDate(endDate)); final long endMilli = c.getTimeInMillis() + c.getTimeZone().getOffset(c.getTimeInMillis()); return (int) ((endMilli - startMilli) / MILLISECONDS_PER_DAY); } /** * Trims the date so that only the day, month, and year are significant. * * @param date date to trim * @return leveled date */ public static Date trimDate(final Date date) { final GregorianCalendar c = gregorianCalendarThreadLocal.get(); c.setTime(date); c.set(Calendar.MILLISECOND, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.HOUR_OF_DAY, 0); return c.getTime(); } }