Java Day Count getDayCount(String from, String to)

Here you can find the source of getDayCount(String from, String to)

Description

get Day Count

License

Open Source License

Declaration

public static int getDayCount(String from, String to) throws ParseException 

Method Source Code


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

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

import java.util.Date;

import java.util.Locale;

public class Main {
    private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    public static int getDayCount(String from, String to) throws ParseException {

        long duration = getTimeCount(from, to, DATE_FORMAT.toPattern());

        return (int) (duration / (1000 * 60 * 60 * 24));
    }// w  w w .  ja v a  2s .c om

    public static long getTimeCount(String from, String to, String format) throws ParseException {

        Date d1 = dateFormatCheck(from, format);
        Date d2 = dateFormatCheck(to, format);

        long duration = d2.getTime() - d1.getTime();

        return duration;
    }

    public static Date dateFormatCheck(String source, String format) throws ParseException {

        if (source == null) {
            throw new ParseException("date string to check is null", 0);
        }

        if (format == null) {
            throw new ParseException("format string to check date is null", 0);
        }

        SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.KOREA);

        Date date = null;

        try {
            date = formatter.parse(source);
        } catch (ParseException e) {
            throw new ParseException(" wrong date:\"" + source + "\" with format \"" + format + "\"", 0);
        }

        if (!formatter.format(date).equals(source)) {
            throw new ParseException("Out of bound date:\"" + source + "\" with format \"" + format + "\"", 0);
        }

        return date;
    }

    public static Date parse(String datetime) {
        try {
            return FORMAT.parse(datetime);
        } catch (ParseException e) {
            return new Date();
        }
    }

    public static String format(Date date) {
        return FORMAT.format(date);
    }
}

Related

  1. getDayCount(String from, String to)
  2. getDayCount(String yyyy_mm_dd_1, String yyyy_mm_dd_2)
  3. GetDays(String strStartDate, String strEndDate)
  4. getDaysBetween(Calendar d1, Calendar d2)
  5. getDaysBetween(Map params)