Java SQL Date getDiffDays(String begin_dt, String end_dt)

Here you can find the source of getDiffDays(String begin_dt, String end_dt)

Description

get Diff Days

License

Open Source License

Declaration

public static int getDiffDays(String begin_dt, String end_dt) 

Method Source Code

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

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

public class Main {
    public static int getDiffDays(String begin_dt, String end_dt) {
        Date end = java.sql.Date.valueOf(end_dt);
        Date begin = java.sql.Date.valueOf(begin_dt);
        int days = getDaysBetween(begin, end);
        return days;
    }/* w  ww . jav a  2s.  co  m*/

    public static int getDaysBetween(Date start, Date end) {
        if (start == null)
            return 0;
        boolean negative = false;
        if (end.before(start)) {
            negative = true;
            Date temp = start;
            start = end;
            end = temp;
        }
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime(start);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        GregorianCalendar calEnd = new GregorianCalendar();
        calEnd.setTime(end);
        calEnd.set(Calendar.HOUR_OF_DAY, 0);
        calEnd.set(Calendar.MINUTE, 0);
        calEnd.set(Calendar.SECOND, 0);
        calEnd.set(Calendar.MILLISECOND, 0);
        if (cal.get(Calendar.YEAR) == calEnd.get(Calendar.YEAR)) {
            if (negative)
                return (calEnd.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR)) * -1;
            return calEnd.get(Calendar.DAY_OF_YEAR) - cal.get(Calendar.DAY_OF_YEAR);
        }
        int counter = 0;
        while (calEnd.after(cal)) {
            cal.add(Calendar.DAY_OF_YEAR, 1);
            counter++;
        }
        if (negative)
            return counter * -1;
        return counter;
    }

    public static int get(Date date, int type) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.get(type);
    }
}

Related

  1. convertTo(final Class> clazz, Object obj)
  2. getClasses()
  3. getCurrDay()
  4. getCurrentYear()
  5. getDayOfPerMonth(String theDataStr)
  6. getEndWeekDayOfMonth(String year, String month)
  7. getFileName()
  8. getFirstDayOfNextMonth()
  9. getFirstDayOfThisMonth()