shnakkydoodle.common.helpers.DateHelper.java Source code

Java tutorial

Introduction

Here is the source code for shnakkydoodle.common.helpers.DateHelper.java

Source

/*
 * Author Stephen Booysen
 *
 * Copyright (c) 2015 Stephen Booysen, Inc. All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * Stephen Booysen. ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Stephen Booysen
 *
 * Stephen Booysen MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
 * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
 * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
 * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */
package shnakkydoodle.common.helpers;

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

import org.joda.time.DateTime;
import org.joda.time.Months;

/**
 * @author Stephen Booysen
 *
 */
public class DateHelper {

    // region Public Members

    /**
     * Try and evaluate the string and return a date with yyyy-MM-dd format
     * 
     * @param input
     * @return
     */
    public static String ourFormat(Date dt) {

        try {
            return new SimpleDateFormat("yyyy-MM-dd").format(dt);
        } catch (Exception e) {
        }

        return null;
    }

    /**
     * Try and evaluate the string and return a date with yyyy-MM-dd format
     * 
     * @param input
     * @return
     */
    public static String ourFormatWithTime(Date dt) {

        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dt);
        } catch (Exception e) {
        }

        return null;
    }

    /**
     * Try and evaluate the string and return a date with yyyy/MM/dd format
     * 
     * @param input
     * @return
     */
    public static String ourFormatWithSlash(Date dt) {

        try {
            return new SimpleDateFormat("yyyy/MM/dd").format(dt);
        } catch (Exception e) {
        }

        return null;
    }

    /**
     * Try and evaluate the string and return a date
     * 
     * @param input
     * @return
     */
    public static Date parse(String input) {

        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(input);
        } catch (Exception e) {
        }

        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(input);
        } catch (Exception e) {
        }

        try {
            return new SimpleDateFormat("yyyy-MM-dd").parse(input);
        } catch (Exception e) {
        }

        try {
            return new SimpleDateFormat("yyyy/MM/dd").parse(input);
        } catch (Exception e) {
        }

        try {
            return new SimpleDateFormat("dd MMM yyyy").parse(input);
        } catch (Exception e) {
        }

        try {
            return new SimpleDateFormat("dow mon dd hh:mm:ss zzz yyyy").parse(input);
        } catch (Exception e) {
        }

        try {
            return new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy").parse(input);
        } catch (Exception e) {

        }
        try {
            return new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse(input);
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * Try to evaluate a date and return a string
     * 
     * @param input
     * @return
     */
    public static String parse(Date input) {

        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(input);
        } catch (Exception e) {
        }

        try {
            return new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(input);
        } catch (Exception e) {
        }

        return null;
    }

    /**
     * Try to evaluate a date and return a string
     * 
     * @param input
     * @return
     */
    public static String parse(Date input, String format) {

        try {
            return new SimpleDateFormat(format).format(input);

        } catch (Exception e) {
        }

        return null;
    }

    /**
     * sets all the time related fields to ZERO!
     *
     * @param date
     *
     * @return Date with hours, minutes, seconds and ms set to ZERO!
     */
    public static Date zeroTime(final Date date) {
        DateFormat format = new SimpleDateFormat("dd.MM.yyyy");
        Date trimmed = null;
        try {
            trimmed = format.parse(format.format(date));
        } catch (ParseException e) {
        } // will never happen
        return trimmed;
    }

    /**
     * sets all the time related fields to end of day!
     *
     * @param date
     *
     * @return Date with hours, minutes, seconds and ms set to ZERO!
     */
    public static Date endTime(final Date date) {
        return DateHelper.setTime(date, 23, 59, 59, 000);
    }

    /**
     * Return the start of a year for a date
     * 
     * @param date
     * @return
     */
    public static Date startOfYear(final Date date) {
        Calendar calendarStart = Calendar.getInstance();
        calendarStart.setTime(date);
        calendarStart.set(Calendar.MONTH, 0);
        calendarStart.set(Calendar.DAY_OF_MONTH, 1);
        return DateHelper.setTime(calendarStart.getTime(), 00, 00, 00, 000);
    }

    /**
     * Return the end of a year for a date
     * 
     * @param date
     * @return
     */
    public static Date endOfYear(final Date date) {
        Calendar calendarStart = Calendar.getInstance();
        calendarStart.setTime(date);
        calendarStart.set(Calendar.MONTH, 11);
        calendarStart.set(Calendar.DAY_OF_MONTH, 31);
        return DateHelper.setTime(calendarStart.getTime(), 23, 59, 59, 000);
    }

    /**
     * sets all the time related fields to start of day!
     *
     * @param date
     *
     * @return Date with hours, minutes, seconds and ms set to ZERO!
     */
    public static Date startTime(final Date date) {
        return DateHelper.setTime(date, 00, 00, 00, 000);
    }

    /**
     * Set the time of the given Date
     *
     * @param date
     * @param hourOfDay
     * @param minute
     * @param second
     * @param ms
     *
     * @return new instance of java.util.Date with the time set
     */
    public static Date setTime(final Date date, final int hourOfDay, final int minute, final int second,
            final int ms) {
        final GregorianCalendar gc = new GregorianCalendar();
        gc.setTime(date);
        gc.set(Calendar.HOUR_OF_DAY, hourOfDay);
        gc.set(Calendar.MINUTE, minute);
        gc.set(Calendar.SECOND, second);
        gc.set(Calendar.MILLISECOND, ms);
        return gc.getTime();
    }

    /**
     * Calculate the number of days between 2 dates
     * 
     * @param fromdate
     * @param todate
     * @return
     */
    public static int yearsBetween(final Date futuredate, final Date pastdate) {
        Calendar firstCal = GregorianCalendar.getInstance();
        Calendar secondCal = GregorianCalendar.getInstance();

        firstCal.setTime(futuredate);
        secondCal.setTime(pastdate);

        firstCal.add(Calendar.DAY_OF_YEAR, -secondCal.get(Calendar.DAY_OF_YEAR));

        return firstCal.get(Calendar.YEAR) - secondCal.get(Calendar.YEAR);
    }

    /**
     * Calculate the number of months between 2 dates
     * 
     * @param fromdate
     * @param todate
     * @return
     */
    public static int monthsBetween(final Date futuredate, final Date pastdate) {
        if (futuredate.equals(pastdate)) {
            return 1;
        }
        DateTime startDate = new DateTime(pastdate.getTime());
        DateTime endDate = new DateTime(futuredate.getTime());
        return Months.monthsBetween(startDate.withDayOfMonth(1), endDate.withDayOfMonth(1)).getMonths();
    }

    /**
     * Calculate the number of days between 2 dates
     * 
     * @param fromdate
     * @param todate
     * @return
     */
    public static int daysBetween(Date futuredate, Date pastdate) {

        if (futuredate.equals(pastdate)) {
            return 1;
        }

        return (int) ((futuredate.getTime() - pastdate.getTime()) / (1000 * 60 * 60 * 24) * -1);
    }

    /**
     * Calculate the number of days between 2 dates
     * 
     * @param fromdate
     * @param todate
     * @return
     */
    public static int hrsBetween(Date futuredate, Date pastdate) {

        if (futuredate.equals(pastdate)) {
            return 1;
        }
        long futureTime = futuredate.getTime();
        long pastTime = pastdate.getTime();
        long period = -1000 * 60 * 60;
        double hours = 1.0 * (futureTime - pastTime) / (period);
        return (int) hours;
    }

    /**
     * Add a number of years
     * 
     * @param dt
     * @param years
     * @return
     */
    public static Date addYears(Date dt, int interval) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        cal.add(Calendar.YEAR, interval);
        return cal.getTime();
    }

    /**
     * Add a number of years
     * 
     * @param dt
     * @param years
     * @return
     */
    public static Date addMonths(Date dt, int interval) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        cal.add(Calendar.MONTH, interval);
        return cal.getTime();
    }

    /**
     * Add a number of days
     * 
     * @param dt
     * @param days
     * @return
     */
    public static Date addDays(Date dt, int interval) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        cal.add(Calendar.DATE, interval);
        return cal.getTime();
    }

    /**
     * Add a number of hours
     * 
     * @param dt
     * @param days
     * @return
     */
    public static Date addHours(Date dt, int interval) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        cal.add(Calendar.HOUR, interval);
        return cal.getTime();
    }

    /**
     * Add a number of hours
     * 
     * @param dt
     * @param days
     * @return
     */
    public static Date addMinutes(Date dt, int interval) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        cal.add(Calendar.MINUTE, interval);
        return cal.getTime();
    }

    /**
     * Get the start of the month
     * 
     * @param dt
     * @return
     */
    public static Date getStartOfMonth(Date dt) {

        Calendar c = Calendar.getInstance();
        c.setTime(dt);
        c.set(Calendar.DAY_OF_MONTH, 1);

        return c.getTime();
    }

    /**
     * Get the edn of the month
     * 
     * @param dt
     * @return
     */
    public static Date getEndOfMonth(Date dt) {

        Calendar c = Calendar.getInstance();
        c.setTime(dt);
        c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));

        return c.getTime();
    }

    /**
     * Get the edn of the month
     * 
     * @param dt
     * @return
     */
    public static Date getMidOfMonth(Date dt) {

        Calendar c = Calendar.getInstance();
        c.setTime(dt);
        c.set(Calendar.DAY_OF_MONTH, 15);

        return c.getTime();
    }

    /**
     * Subtract a number of days
     * 
     * @param dt
     * @param days
     * @return
     */
    public static Date subtractDays(Date dt, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        cal.add(Calendar.DATE, -days);
        return cal.getTime();
    }

    /**
     * Retrieves the original date by current date and an age.
     * 
     * @param currentDate
     * @param age
     * @return
     */
    public static Date getDateFromDateAge(Date currentDate, String age) {
        Calendar cal = Calendar.getInstance();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String nowString = sdf.format(currentDate);
            cal.setTime(sdf.parse(nowString));
        } catch (ParseException e) {
            cal.setTime(currentDate);
        }
        if (age.contains("m") || age.contains("M")) {
            age = age.replace("m", "");
            age = age.replace("M", "");
            int months = Integer.parseInt(age) * -1;
            cal.add(Calendar.MONTH, months);
        } else {
            double years = Double.parseDouble(age) * -1;
            cal.add(Calendar.YEAR, (int) years);
        }
        return cal.getTime();
    }

    /**
     * Returns age given the date of birth
     * 
     * @param dob
     * @return
     * @throws Exception
     */
    public static Integer getAge(Calendar dob) throws Exception {
        Calendar today = Calendar.getInstance();
        int curYear = today.get(Calendar.YEAR);
        int dobYear = dob.get(Calendar.YEAR);
        int age = curYear - dobYear;

        int curMonth = today.get(Calendar.MONTH);
        int dobMonth = dob.get(Calendar.MONTH);
        if (dobMonth > curMonth) {
            age--;
        } else if (dobMonth == curMonth) {
            int curDay = today.get(Calendar.DAY_OF_MONTH);
            int dobDay = dob.get(Calendar.DAY_OF_MONTH);
            if (dobDay > curDay) {
                age--;
            }
        }
        return age;
    }

    /**
     * Returns true if toCompare is before or on same day as date. it only compares yyyy-MM-dd and will assume HH:mm:ss to be 00:00:00
     * 
     * @param date
     * @param toCompare
     * @return
     */
    public static boolean isBeforeOrEqual(Date date, Date toCompare) {
        if (date == null || toCompare == null) {
            return false;
        }
        date = zeroTime(date);
        toCompare = zeroTime(toCompare);
        return toCompare.compareTo(date) >= 0;
    }

    /**
     * Returns true if toCompare is after or on same day as date. it only compares yyyy-MM-dd and will assume HH:mm:ss to be 00:00:00
     * 
     * @param date
     * @param toCompare
     * @return
     */
    public static boolean isAfterOrEqual(Date date, Date toCompare) {
        if (date == null || toCompare == null) {
            return false;
        }
        date = zeroTime(date);
        toCompare = zeroTime(toCompare);
        return toCompare.compareTo(date) <= 0;
    }

    /**
     * 
     * @param dob
     * @return
     * @throws Exception
     */
    public static Integer getAgeFromDateofBirth(String dob) throws Exception {

        Calendar birth = new GregorianCalendar();
        Calendar today = new GregorianCalendar();
        int age = 0;
        int factor = 0; // to correctly calculate age when birthday has not been yet celebrated
        Date birthDate = parse(dob);
        Date currentDate = new Date(); // current date

        if (birthDate == null) {
            return age;
        }

        birth.setTime(birthDate);
        today.setTime(currentDate);

        // check if birthday has been celebrated this year
        if (today.get(Calendar.DAY_OF_YEAR) < birth.get(Calendar.DAY_OF_YEAR)) {
            factor = -1; // birthday not celebrated
        }
        age = today.get(Calendar.YEAR) - birth.get(Calendar.YEAR) + factor;

        return age;
    }

    /**
     * 
     * @param dob
     * @param date
     * @return
     * @throws Exception
     */
    public static Integer getAgeFromDateofBirth(String dob, Date date) throws Exception {

        Calendar birth = new GregorianCalendar();
        Calendar today = new GregorianCalendar();
        int age = 0;
        int factor = 0; // to correctly calculate age when birthday has not been yet celebrated
        Date birthDate = parse(dob);

        if (birthDate == null) {
            return age;
        }

        birth.setTime(birthDate);
        today.setTime(date);

        // check if birthday has been celebrated this year
        if (today.get(Calendar.DAY_OF_YEAR) < birth.get(Calendar.DAY_OF_YEAR)) {
            factor = -1; // birthday not celebrated
        }
        age = today.get(Calendar.YEAR) - birth.get(Calendar.YEAR) + factor;

        return age;
    }

    // endregion

}