Java Day Count getDaysBetween(Calendar d1, Calendar d2)

Here you can find the source of getDaysBetween(Calendar d1, Calendar d2)

Description

get Days Between

License

Open Source License

Declaration

public static int getDaysBetween(Calendar d1, Calendar d2) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.text.ParseException;
import java.text.SimpleDateFormat;

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

public class Main {
    public static int getDaysBetween(Calendar d1, Calendar d2) {
        if (d1.after(d2)) { // swap dates so that d1 is start and d2 is end
            Calendar swap = d1;// w ww  . j  a  v  a 2 s  .  co  m
            d1 = d2;
            d2 = swap;
        }
        int days = d2.get(Calendar.DAY_OF_YEAR) - d1.get(Calendar.DAY_OF_YEAR);
        int y2 = d2.get(Calendar.YEAR);
        if (d1.get(Calendar.YEAR) != y2) {
            d1 = (Calendar) d1.clone();
            do {
                days += d1.getActualMaximum(Calendar.DAY_OF_YEAR);
                d1.add(Calendar.YEAR, 1);
            } while (d1.get(Calendar.YEAR) != y2);
        }
        return days;
    }

    public static int getDaysBetween(String beginDate, String endDate) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date bDate = null;
        Date eDate = null;
        try {
            bDate = format.parse(beginDate);
            eDate = format.parse(endDate);
        } catch (ParseException e) {
            return -1;
        }
        Calendar d1 = new GregorianCalendar();
        d1.setTime(bDate);
        Calendar d2 = new GregorianCalendar();
        d2.setTime(eDate);
        int days = d2.get(6) - d1.get(6);
        int y2 = d2.get(1);
        if (d1.get(1) != y2) {
            d1 = (Calendar) d1.clone();
            do {
                days += d1.getActualMaximum(6);
                d1.add(1, 1);
            } while (d1.get(1) != y2);
        }
        return days;
    }
}

Related

  1. getDayCount(String from, String to)
  2. getDayCount(String from, String to)
  3. getDayCount(String yyyy_mm_dd_1, String yyyy_mm_dd_2)
  4. getDaySub(String beginDate, String endDate)
  5. getDaySub(String start_time, String end_time)
  6. getDaysBetween(Map params)
  7. getDaysBetweenTwoDays(String dateFrom, String dateEnd)
  8. GetDays(String strStartDate, String strEndDate)