Java Date Between daysBetween(Date startDate, Date endDate)

Here you can find the source of daysBetween(Date startDate, Date endDate)

Description

days Between

License

Open Source License

Declaration

public static long daysBetween(Date startDate, Date endDate) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2010 Robert "Unlogic" Olofsson (unlogic@unlogic.se).
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser Public License v3
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-3.0-standalone.html
 ******************************************************************************/

import java.util.Calendar;
import java.util.Date;

public class Main {
    public static long daysBetween(Date startDate, Date endDate) {

        Calendar start = Calendar.getInstance();
        start.setTime(startDate);/*from   w w w . j  ava  2 s . c om*/

        Calendar end = Calendar.getInstance();
        end.setTime(endDate);

        return daysBetween(start, end);
    }

    public static long daysBetween(Calendar startDate, Calendar endDate) {

        startDate = (Calendar) startDate.clone();

        long daysBetween = 0;

        while (startDate.get(Calendar.YEAR) < endDate.get(Calendar.YEAR)) {

            if (startDate.get(Calendar.DAY_OF_YEAR) != 1) {

                int diff = startDate.getMaximum(Calendar.DAY_OF_YEAR) - startDate.get(Calendar.DAY_OF_YEAR);

                diff++;

                startDate.add(Calendar.DAY_OF_YEAR, diff);

                daysBetween += diff;

            } else {

                daysBetween += startDate.getMaximum(Calendar.DAY_OF_YEAR);

                startDate.add(Calendar.YEAR, 1);
            }
        }

        daysBetween += endDate.get(Calendar.DAY_OF_YEAR) - startDate.get(Calendar.DAY_OF_YEAR);

        return daysBetween;
    }
}

Related

  1. DaysBetween(Date date1, Date date2)
  2. daysBetween(Date smdate, Date bdate)
  3. daysBetween(Date smdate, Date bdate)
  4. daysBetween(Date smdate, Date bdate)
  5. daysBetween(Date smdate, Date bdate)
  6. daysBetween(final Date date1, final Date date2)
  7. daysBetween(final Date dateA, final Date dateB)
  8. daysBetween(String bdate, String edate)
  9. daysBetween(String beginDate, String endDate)