Class DateUtils in java


Sử dụng JDK 1.5++ . Nếu có method nào có error thì để lại message nha :D

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public final class DateUtils {
    /** Date format in 'yyyy/MM/dd HH:mm:ss'. */
    public static final String DATE_YYYYMMDDHH24MMSS = "yyyy/MM/dd HH:mm:ss";
    /** Date format in 'yyyy/MM/dd HH:mm'. */
    public static final String DATE_YYYYMMDDHH24MM = "yyyy/MM/dd HH:mm";
    /** Date format in 'yyyy/MM/dd HH'. */
    public static final String DATE_YYYYMMDDHH = "yyyy/MM/dd HH";
    /** Date format in 'yyyy/MM/dd'. */
    public static final String DATE_YYYYMMDD = "yyyy/MM/dd";
    /** Date format in 'yyyy/MM'. */
    public static final String DATE_YYYYMM = "yyyy/MM";
    /** Date format in 'yyyy-MM-dd'. */
    public static final String TIMESTAMP_YYYYMMDD = "yyyy-MM-dd";
    /** Date format in 'yyyy-MM-dd HH:mm:ss'. */
    public static final String TIMESTAMP_YYYYMMDDHH24MMSS = "yyyy-MM-dd HH:mm:ss";
    /** Date format in 'yyyy-MM-dd HH:mm'. */
    public static final String TIMESTAMP_YYYYMMDDHH24MM = "yyyy-MM-dd HH:mm";
    /** Time format in 'HH:mm'. */
    public static final String TIME_HH24MM = "HH:mm";
    /** Date format in 'yyyyMMddHHmmss'. */
    public static final String DATE_STRING = "yyyyMMddHHmmss";
    /** Date format in 'yyyyMMddHHmmss'. */
    public static final String DATE_STRING_MINUTE = "yyyyMMddHHmm";
    /** Date format in 'yyyyMMddHHmmss'. */
    public static final String DATE_STRING_HOUR = "yyyyMMddHH";
    /** Date format in 'yyyyMMddHHmmss'. */
    public static final String DATE_STRING_DAY = "yyyyMMdd";
    /** Date format in 'yyyyMMddHHmmss'. */
    public static final String DATE_STRING_MONTH = "yyyyMM";
    /** Time format in 'HH:mm:ss'. */
    public static final String TIME_HHMMSS = "HH:mm:ss";
    /** The pattern 'yyyyMMdd'. */
    public static final String DATE_PATTERN = "yyyyMMdd";
    /** The pattern 'HHmm'. */
    public static final String TIME_PATTERN = "HHmm";
    /** The pattern 'yyyyMMddHHmm'. */
    public static final String DATE_TIME_PATTERN = "yyyyMMddHHmm";
    /** The pattern 'yyyyMMddHHmmssSSS'. */
    public static final String DATE_TIME_MILISECOND_PATTERN = "yyyyMMddHHmmssSSS";
    /** Time format in 'yyyyMMddHH'.*/
    public static final String TIME_HH24 = "yyyyMMddHH";

    /**
     * Private constructor.
     */
    private DateUtils() {
    }
    /**
     * <p>
     * Get date time from a Timestamp with a specific pattern.
     * </p>
     *
     * @param ts
     *            Timestamp
     * @param pattern
     *            pattern of date time. For example, DATE_YYYYMMDDHH24MMSS,
     *            DATE_YYYYMMDDHH24MM, e.g.
     * @return date time with the pattern
     */
    public static String getDateTime(final Timestamp ts, final String pattern) {
        final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(ts.getTime());
    }

    /**
     * <p>
     * Get date time from a time with a specific pattern.
     * </p>
     *
     * @param time long, in millisecond
     * @param pattern
     *            pattern of date time. For example, DATE_YYYYMMDDHH24MMSS,
     *            DATE_YYYYMMDDHH24MM, e.g.
     * @return date time with the pattern
     */
    public static String getDateTime(final long time, final String pattern) {
        final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(time);
    }

    /**
     * <p>
     * Get date time from a Date with a specific pattern.
     * </p>
     *
     * @param date the date
     * @param pattern
     *            pattern of date time. For example, DATE_YYYYMMDDHH24MMSS,
     *            DATE_YYYYMMDDHH24MM, e.g.
     * @return date time with the pattern
     */
    public static String getDateTime(final Date date, final String pattern) {
        final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    /**
     * <p>
     * Parse date string to Date object.
     * </p>
     *
     * @param timeStr
     *            Date string
     * @param pattern
     *            Pattern to parse
     * @return Date object null if date string is invalid date
     * @throws ParseException
     *             ParseException
     */
    public static Date parseDate(final String timeStr, final String pattern)
            throws ParseException {
        final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        sdf.setLenient(false);
        return sdf.parse(timeStr);
    }

    /**
     * <p>
     * Format string of date into format same as pattern.
     * </p>
     *
     * @param date
     *            Date
     * @param pattern
     *            Pattern to format
     * @throws ParseException
     *             ParseException
     * @return String string of date into format same as pattern
     */
    public static String formatDate(final Date date, final String pattern)
            throws ParseException {
        final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    /**
     * <p>
     * Add time to Date object.
     * </p>
     *
     * @param date
     *            Date object to add
     * @param field
     *            Field in Date object (year, month,..,second)
     * @param amount
     *            Time amount to add
     * @return Date object after adding
     */
    public static Date addDate(final Date date, final int field,
            final int amount) {
        final Calendar cal = new GregorianCalendar();
        cal.setTime(date);
        cal.add(field, amount);
        return cal.getTime();
    }

    /**
     * <p>
     * input date for format.
     * </p>
     *
     * @param aMask
     *            format Data
     * @param aDate
     *            data
     * @return returnValue return value
     */
    public static String getDateTime(final String aMask, final Date aDate) {
        String returnValue = "";
        if (null != aDate) {
            final SimpleDateFormat df = new SimpleDateFormat(aMask);
            returnValue = df.format(aDate);
        }

        return (returnValue);
    }

    /**
     * <p>
     * Parse time string to object Timestamp.
     * </p>
     *
     * @param timeStr
     *            Time string to parse
     * @param pattern
     *            Pattern to parse
     * @return Timestamp object
     */
    public static Timestamp parseTimestamp(final String timeStr,
            final String pattern) {
        Timestamp ts = null;
        try {
            final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            sdf.setLenient(false);
            final Date date = sdf.parse(timeStr);
            ts = new Timestamp(date.getTime());
        } catch (ParseException e) {
            ts = null;
        }
        return ts;
    }

    /**
     * <p>
     * Remove hour, minute, second and milisecond from Date object.
     * </p>
     *
     * @param date
     *            Date object to remove
     * @return Date objec is removed these
     */
    public static Date removeHour(final Date date) {
        final Calendar cal = new GregorianCalendar();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * <p>
     * Calculate distance (in day) between 2 Date object.
     * </p>
     *
     * @param from
     *            From date
     * @param to
     *            To date
     * @return Number of days different -1 if from > to
     */
    public static int distanceBetween2Dates(final Date from, final Date to) {
        final Calendar calFrom = new GregorianCalendar();
        calFrom.setTime(from);
        final Calendar calTo = new GregorianCalendar();
        calTo.setTime(to);
        final long dis = calTo.getTimeInMillis() - calFrom.getTimeInMillis();
        if (dis < 0) {
            return -1;
        }
        final long dateInMiliSeconds = 1000 * 60 * 60 * 24;
        return (Math.round((dis / (dateInMiliSeconds))));

    }

    /**
     * <p>
     * Calculate distance (in second) between 2 dates.
     * </p>
     *
     * @param from
     *            From date
     * @param to
     *            To date
     * @return Number of second different -1 if from > to
     *
     * @exception
     *          ParseException
     */
    public static int distanceBetween2DatesInSecond(final String fromDate,
            final String toDate, final String pattern) throws ParseException {
        final SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        final Calendar calFrom = new GregorianCalendar();
        calFrom.setTime(dateFormat.parse(fromDate));
        final Calendar calTo = new GregorianCalendar();
        calTo.setTime(dateFormat.parse(toDate));
        final long dis = calTo.getTimeInMillis() - calFrom.getTimeInMillis();
        if (dis < 0) {
            return -1;
        }
        final long secondInMiliSeconds = 1000;
        final long distantInSecond = dis / secondInMiliSeconds;
        return Math.round(distantInSecond);
    }

    /**
     * <p>
     * Calculate distance (in minute) between 2 dates.
     * </p>
     *
     * @param from
     *            From date
     * @param to
     *            To date
     * @return Number of minute different -1 if from > to
     *
     * @exception
     *          ParseException
     */
    public static int distanceBetween2DatesInMinute(final String fromDate,
            final String toDate, final String pattern) throws ParseException {
        final SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        final Calendar calFrom = new GregorianCalendar();
        calFrom.setTime(dateFormat.parse(fromDate));
        final Calendar calTo = new GregorianCalendar();
        calTo.setTime(dateFormat.parse(toDate));
        final long dis = calTo.getTimeInMillis() - calFrom.getTimeInMillis();
        if (dis < 0) {
            return -1;
        }
        final long minuteInMiliSeconds = 1000 * 60;
        final long distantInMinute = dis / minuteInMiliSeconds;
        return Math.round(distantInMinute);
    }

    /**
     * <p>
     * Calculate distance (in hour) between 2 dates.
     * BugID: QM-3.0IT-0143 - Change the validation of From Date and To Date in Exporter.
     * </p>
     *
     * @param from
     *            From date
     * @param to
     *            To date
     * @return Number of hour different <br>-1 if from > to
     */
    public static int distanceBetween2DatesInHour(final Date fromDate,
            final Date toDate) {
        final Calendar calFrom = new GregorianCalendar();
        calFrom.setTime(fromDate);
        final Calendar calTo = new GregorianCalendar();
        calTo.setTime(toDate);
        final long dis = calTo.getTimeInMillis() - calFrom.getTimeInMillis();
        if (dis < 0) {
            return -1;
        }
        final long hourInMiliSeconds = 1000 * 60 * 60;
        return (Math.round((dis / (hourInMiliSeconds))));
    }

    /**
     * <p>
     * Check file in around numMinutes minutes.
     * </p>
     *
     * @param first :
     *            Calendar time of CSV file
     * @param last :
     *            Calendar time of system
     * @param numMinutes :
     *            number of minutes
     * @return : true : if file in around numMinutes
     */
    public static boolean checkFileInNMinutes(final Calendar first,
            final Calendar last, final int numMinutes) {
        boolean result = false;
        long duration = last.getTimeInMillis() - first.getTimeInMillis();
        if (duration >= 0) {
            final int minuteInMili = 60 * 1000;
            result = (duration <= (numMinutes * minuteInMili));
        }
        return result;
    }
    /**
     * <p>
     * Compare 2 date.
     * </p>
     *
     * @param Date1
     *            date 1
     * @param Date2
     *            date 2
     * @return 1 : if date1 > date2 <br/> 0 : if date1 == date2 <br/> -1 : if
     *         date 1 < date2 <br/>
     */
    public static int compare2Date(final Date date1, final Date date2) {
        int result = 0;
        final int distance = distanceBetween2Dates(date1, date2);
        if (distance > 0) {
            result = -1;
        } else if (distance < 0) {
            result = 1;
        } else {
            result = 0;
        }
        return result;
    }
    /**
     * <p>
     * Get previous date of the date N days.
     * </p>
     *
     * @param numPreviousDay
     *            number of days
     * @param date
     *            the date which based to get previous date
     * @param pattern
     *            the pattern to format date. For example, 'yyyy/MM/dd'.
     * @return String of date in format pattern
     * @throws ParseException
     *             if the date is invalid date format
     */
    public static String getPreviousDate(final int numPreviousDay,
            final String date, final String pattern) throws ParseException {
        final long millsInDate = 1000 * 60 * 60 * 24;
        final SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        final long lDate = dateFormat.parse(date).getTime()
                - (millsInDate * numPreviousDay);
        return dateFormat.format(lDate);
    }

    /**
     * <p>
     * Get previous hour of the date.
     * </p>
     *
     * @param numPreviousHour
     *            number of hour
     * @param date
     *            the date which based to get previous date
     * @param pattern
     *            the pattern to format date. For example, 'yyyy/MM/dd'.
     * @return String of date in format pattern
     * @throws ParseException
     *             if the date is invalid date format
     */
    public static Date getPreviousHour(final int numPreviousHour, final Date date) {
        final Calendar c = Calendar.getInstance();
        c.setTime(date);
        final long millsInHour = 1000 * 60 * 60;
        final long lPrevHour = c.getTimeInMillis()
                - (numPreviousHour * millsInHour);
        c.setTimeInMillis(lPrevHour);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        return c.getTime();
    }

    /**
     * <p>
     * Get next time of input date with distant is input number of minute.
     * </p>
     *
     * @param numMinute
     *            number of minute
     * @param date
     *            the date which based to get next date
     * @return next date of input date
     */
    public static String getNextTime(final int numMinute, final String date,
            final String pattern) throws ParseException {
        final SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
        final Calendar c = Calendar.getInstance();
        c.setTime(dateFormat.parse(date));
        final long millsInMinute = 1000 * 60;
        final long nextTime = c.getTimeInMillis() + (numMinute * millsInMinute);
        c.setTimeInMillis(nextTime);
        return formatDate(c.getTime(), pattern);
    }

    /**
     * <p>
     * Get previous date of the date N days.
     * </p>
     *
     * @param numPreviousDay
     *            number of days
     * @param date
     *            the date which based to get previous date
     * @return previous date
     */
    public static Date getPreviousDate(final int numPreviousDay, final Date date) {
        final Calendar c = Calendar.getInstance();
        c.setTime(date);
        final long millsInDate = 1000 * 60 * 60 * 24;
        final long lPrevDate = c.getTimeInMillis()
                - (numPreviousDay * millsInDate);
        c.setTimeInMillis(lPrevDate);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);

        return c.getTime();
    }
    /**
     * <p>
     * Get previous time stamp based on a given number of minutes.
     * </p>
     * @param numPrevMinute Number of minutes
     * @param timestamp The based time stamp
     * @return Previous time stamp
     */
    public static Timestamp getPreviousTimestamp(final int numPrevMinute, final Timestamp timestamp) {
        final long miliSecondOfMinute = 60 * 1000;
        return new Timestamp(timestamp.getTime() - (numPrevMinute * miliSecondOfMinute));
    }
    /**
     * <p>
     * Get next time stamp based on a given number of minutes.
     * </p>
     * @param numNextMinute Number of minutes
     * @param timestamp The based time stamp
     * @return Next time stamp
     */
    public static Timestamp getNextTimestamp(final Timestamp timestamp, final int numNextMinute) {
        final long miliSecondOfMinute = 60 * 1000;
        return new Timestamp(timestamp.getTime() + (numNextMinute * miliSecondOfMinute));
    }

    /**
     * <p>
     * Check a string of date or time with a given pattern.
     * </p>
     *
     * @param strDate
     *            string of date or time
     * @param pattern
     *            the pattern will be used to check
     * @return
     * @see (Related item)
     */
    public static boolean checkDateTime(final String strDate,
            final String pattern) {
        boolean succes = false;
        try {
            final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            final Date d = sdf.parse(strDate);
            // Double check
            if (strDate.equals(sdf.format(d))) {
                succes = true;
            }
        } catch (ParseException e) {
            succes = false;
        }
        return succes;
    }

    /**
     * <p>
     * Get the previous date of N months.
     * </p>
     * @param numMonth number of month
     * @param date the date which based to get the previous date
     * @return the result previous date
     */
    public static Date getPreviousDateByMonth(final int numMonth, final Date date) {
        final Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.MONTH, 0 - numMonth);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        return cal.getTime();
    }

    /**
     * <p>
     * Build a custom time-stamp with a given time-stamp. <br>
     * For example, <br>
     *  1) Input '2009-12-14 12:02:34' <br>
     *  2) secondMinuteHourDay is [20, 59] <br>
     *  The output is '2009-12-14 12:20:59'
     * </p>
     * @param inputTimestamp The inputed time stamp
     * @param secondMinuteHour The value of second, minute and hour will be added to returned time stamp. <br>
     *                            NOTE: <br>
     *                             - 1st element is second [0..59] <br>
     *                             - 2nd is minute [0..59] <br>
     *                             - 3rd is hour [0..23] <br>
     * @return Timestamp
     */
    public static Timestamp buildCustomTimestamp(final Timestamp inputTimestamp, final int... secondMinuteHour) {
        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(inputTimestamp.getTime());
        final int secondIndex = 0;
        if (secondMinuteHour != null && secondMinuteHour.length > secondIndex) {
            calendar.set(Calendar.SECOND, secondMinuteHour[secondIndex]);
        }
        final int minuteIndex = 1;
        if (secondMinuteHour != null && secondMinuteHour.length > minuteIndex) {
            calendar.set(Calendar.MINUTE, secondMinuteHour[minuteIndex]);
        }
        final int hourIndex = 2;
        if (secondMinuteHour != null && secondMinuteHour.length > hourIndex) {
            calendar.set(Calendar.HOUR_OF_DAY, secondMinuteHour[hourIndex]);
        }
        return new Timestamp(calendar.getTimeInMillis());
    }
    /**
     * <p>
     * Build a custom time-stamp exactly to month based on inputed timestamp.<br>
     * For example, <br>
     * FROM: '2009-12-11 12:01:32' -> '2009-12-01 00:00:00' <br>
     * TO  : '2009-02-11 11:05:37' -> '2009-02-28 23:59:59' <br>
     * </p>
     * @param inputTimestamp The inputed timestamp
     * @param isTO True if build TO timestamp, otherwise build FROM timestamp
     * @return Timestamp
     */
    public static Timestamp buildCustomTimestampWithMonth(final Timestamp inputTimestamp, final boolean isTO) {
        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(inputTimestamp.getTime());
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        //Set to next month (00:00:00 of the 1st day of the next month) => Back one minute to get last day of the month
        if (isTO) {
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1);
            calendar.setTimeInMillis(calendar.getTimeInMillis() - 1000);
        }
        return new Timestamp(calendar.getTimeInMillis());
    }

    /**
     * <p>
     * inputTimestamp = "2009-01-01 12:12:12". <br>
     * hour = 00, minute = 00, second=00 <br>
     * If isTo == false --> Return value = "2009-01-01 00:00:00" <br>
     * Else --> Return value = "2008-12-31 00:00:00" <br>
     * </p>
     * @param inputTimestamp The inputed timestamp.
     * @param isTO True if build TO timestamp, otherwise build FROM timestamp.
     * @param hour The new hour value.
     * @param minute The new minute value.
     * @param second The new second value.
     * @return
     */
    public static Timestamp buildCustomTimestampWithMonth(final Timestamp inputTimestamp, final boolean isTO,
                            final int hour, final int minute, final int second) {
        final int milis = 1000;
        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(inputTimestamp.getTime());
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        //Set to next month (00:00:00 of the 1st day of the next month) => Back one minute to get last day of the month
        if (isTO) {
            calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
            calendar.setTimeInMillis(calendar.getTimeInMillis() - milis);
        }
        return buildCustomTimestamp(new Timestamp(calendar.getTimeInMillis()), second, minute, hour);
    }

    /**
     * <p>
     * Get number of months of FROM and TO.
     * </p>
     * @param from The time stamp (FROM)
     * @param to The time stamp (TO)
     * @return Number of month between FROM and TO if FROM <= TO, otherwise return -1
     */
    public static int getNumMonth(final Timestamp from, final Timestamp to) {
        if (from == null || to == null) {
            return -1;
        }
        final Calendar calFrom = Calendar.getInstance();
        calFrom.setTime(from);
        calFrom.set(Calendar.DAY_OF_MONTH, 1);
        calFrom.set(Calendar.HOUR_OF_DAY, 0);
        calFrom.set(Calendar.MINUTE, 0);
        calFrom.set(Calendar.SECOND, 0);
        calFrom.set(Calendar.MILLISECOND, 0);

        final Calendar calTo = Calendar.getInstance();
        calTo.setTime(to);
        calTo.set(Calendar.DAY_OF_MONTH, 1);
        calTo.set(Calendar.HOUR_OF_DAY, 0);
        calTo.set(Calendar.MINUTE, 0);
        calTo.set(Calendar.SECOND, 0);
        calTo.set(Calendar.MILLISECOND, 0);
        if (calFrom.getTimeInMillis() > calTo.getTimeInMillis()) {
            return -1;
        }
        int numMonth = 0;
        while (calFrom.getTimeInMillis() < calTo.getTimeInMillis()) {
            numMonth++;
            calFrom.add(Calendar.MONTH, 1);
        }
        return numMonth;
    }
    /**
     * <p>
     * Get number of days of FROM and TO.
     * </p>
     * @param from The time stamp (FROM)
     * @param to The time stamp (TO)
     * @return Number of month between FROM and TO if FROM <= TO, otherwise return -1
     */
    public static int getNumDay(final Timestamp from, final Timestamp to) {
        if (from == null || to == null) {
            return -1;
        }
        final Calendar calFrom = Calendar.getInstance();
        calFrom.setTime(from);
        calFrom.set(Calendar.HOUR_OF_DAY, 0);
        calFrom.set(Calendar.MINUTE, 0);
        calFrom.set(Calendar.SECOND, 0);
        calFrom.set(Calendar.MILLISECOND, 0);

        final Calendar calTo = Calendar.getInstance();
        calTo.setTime(to);
        calTo.set(Calendar.HOUR_OF_DAY, 0);
        calTo.set(Calendar.MINUTE, 0);
        calTo.set(Calendar.SECOND, 0);
        calTo.set(Calendar.MILLISECOND, 0);
        if (calFrom.getTimeInMillis() > calTo.getTimeInMillis()) {
            return -1;
        }
        final int numMSOfDay = 24 * 60 * 60 * 1000;
        final int numDay = (int) ((calTo.getTimeInMillis() - calFrom.getTimeInMillis()) / numMSOfDay);
        return numDay;
    }

    /**
     * <p>
     * Calculate distance (in day) between 2 Date object with hour, minute, second is 0.
     * </p>
     *
     * @param from
     *            From date
     * @param to
     *            To date
     * @return Number of days different -1 if from > to
     */
    public static int getNumDay(final Date from, final Date to) {
        if (from == null || to == null) {
            return -1;
        }
        final Timestamp timeStampFrom = new Timestamp(from.getTime());
        final Timestamp timeStampTo = new Timestamp(to.getTime());
        return getNumDay(timeStampFrom, timeStampTo);
    }

    /**
     * <p>
     * Validate date parameter with valid pattern yyyyMMdd.
     * </p>
     *
     * @param strDate parameter string date
     * @param paramLength length of date parameter
     * @param beginIdxLastChar begin index of last character
     * @param endIdxLastChar end index of last character
     * @return true if parameter is valid <br>
     *          false if otherwise
     */
    public static boolean validateDate(final String strDate, final int paramLength,
                            final int beginIdxLastChar, final int endIdxLastChar) {
        boolean result = true;
        final int length = strDate.length();
        //check length of parameter = 8
        if (length != paramLength) {
            result = false;
            return result;
        }
        // check the last character
        final String strLastChar = strDate.substring(beginIdxLastChar, endIdxLastChar);
        try {
            Integer.parseInt(strLastChar);
        } catch (NumberFormatException e) {
            result = false;
        }
        return result;
    }

    /**
     * Compare 2 timestamp and return minValue.
     * @param value1 compared value 1
     * @param value2 compared value 2
     * @param datePattern: YYYMMDD, YYYMMDDHH, YYYMMDDHHmm, YYYMMDDHHmmss....
     * @return minValue of (value1, value2)
     */
    public static Timestamp getMinDatetime(final Timestamp value1, final Timestamp value2, final String datePattern) {
        Timestamp minValue = null;
        try {
            if (null != value1 && null != value2) {
                int distance = DateUtils.distanceBetween2DatesInMinute(
                        DateUtils.getDateTime(value1, datePattern),
                        DateUtils.getDateTime(value2, datePattern),  datePattern);
                // value1 > value2
                if (distance < 0) {
                    minValue = value2;
                } else {
                    minValue = value1;
                }
            }
        } catch (Exception e) {
            return null;
        }
        return minValue;
    }

    /**
     * Compare 2 timestamp and return maxValue.
     * @param value1 compared value 1
     * @param value2 compared value 2
     * @param datePattern: YYYMMDD, YYYMMDDHH, YYYMMDDHHmm, YYYMMDDHHmmss....
     * @return maxValue of (value1, value2)
     */
    public static Timestamp getMaxDatetime(final Timestamp value1, final Timestamp value2, final String datePattern) {
        Timestamp maxValue = null;
        try {
            if (null != value1 && null != value2) {
                int distance = DateUtils.distanceBetween2DatesInMinute(
                        DateUtils.getDateTime(value1, datePattern),
                        DateUtils.getDateTime(value2, datePattern),  datePattern);
                // value1 > value2
                if (distance < 0) {
                    maxValue = value1;
                } else {
                    maxValue = value2;
                }
            }
        } catch (Exception e) {
            return null;
        }
        return maxValue;
    }

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: