Java Date Between daysBetween(Date smdate, Date bdate)

Here you can find the source of daysBetween(Date smdate, Date bdate)

Description

days Between

License

Apache License

Parameter

Parameter Description
smdate a parameter
bdate a parameter

Exception

Parameter Description
ParseException an exception

Declaration

public static int daysBetween(Date smdate, Date bdate) throws ParseException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main {
    public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_PATTERN = "yyyy-MM-dd";

    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);/*from w w  w  .ja v  a2 s  .  c  om*/
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);
        return Integer.parseInt(String.valueOf(between_days));
    }

    public static Date parse(String str, String formatPattern) {
        try {
            return new SimpleDateFormat(formatPattern).parse(str);
        } catch (ParseException e) {
            throw new RuntimeException("could not parse date: " + str + " LEGACY_FORMAT = "
                    + new SimpleDateFormat(formatPattern).toPattern(), e);
        }
    }

    public static Date parse(String str) {
        if (str.length() != DATE_PATTERN.length() && str.length() != DATE_TIME_PATTERN.length()) {
            return null;
        }
        String formatPattern = DATE_PATTERN;
        if (str.length() > 10) {
            formatPattern = DATE_TIME_PATTERN;
        }

        try {
            return new SimpleDateFormat(formatPattern).parse(str);
        } catch (ParseException e) {
            throw new RuntimeException("could not parse date: " + str + " LEGACY_FORMAT = "
                    + new SimpleDateFormat(formatPattern).toPattern(), e);
        }
    }

    public static String format(Date date, String formatPattern) {
        // Assert.notNull(date);
        return new SimpleDateFormat(formatPattern).format(date);
    }
}

Related

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