Sep 132011
 

In this post I will share some frequently use methods for Date/Time processing. These methods are needed for almost every project or project starters. Feel free to use and add more features to my class.

First are some Date Time Formatter like date formatter, 24h time formatter, 24h date time formatter…

public static final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
public static final SimpleDateFormat monthYearFormater = new SimpleDateFormat("MM/yyyy");
public static final SimpleDateFormat timeFormatter = new SimpleDateFormat("hh:mm:ss");
public static final SimpleDateFormat datetimeFormatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
public static final SimpleDateFormat datetimeFormatterNoSecond = new SimpleDateFormat("dd/MM/yyyy HH:mm");
public static final SimpleDateFormat hourMinuteFormater = new SimpleDateFormat("HH:mm");
public static final SimpleDateFormat timeStampFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

You will use these formatters to parse String into Date so that you can use for calculation. Or you can use these formatters to format a Date into String so that you can use it to print out a console or notify user via a message.

Next is methods needed to get a Calendar instance, to operate with Date object, you definitely will need Calendar object.

public static Calendar getCalendar(Date date) {
	Calendar c = Calendar.getInstance();
	c.setTime(date);
	return c;
}

public static Calendar getCalendar() {
	Calendar c = Calendar.getInstance();
	c.setTime(new Date());
	return c;
}

Now what if you know date/month/year and want to have a Date object? The following methods will help you to build Date

	/**
	 * Build Date from date/month/year. Zero-based for Month (0=January).
	 * 
	 * @return
	 */
	public static Date buildDate(int year, int month, int date) {
		Calendar calendar = getCalendar();
		calendar.set(year, month, date);
		return calendar.getTime();
	}

	/**
	 * Build Datetime from date/month/year/hour/minute/second. Zero-based for
	 * Month (0=January).
	 * 
	 * @param year
	 * @param month
	 * @param date
	 * @param hour
	 * @param minute
	 * @param second
	 * @return
	 */
	public static Date buildDateTime(int year, int month, int date, int hour, int minute, int second) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month, date, hour, minute, second);
		return calendar.getTime();
	}

Sometime you will also need to remove the Time part from a Datetime object, here is the method for that purpose

	/**
	 * Delete time from Date.
	 * 
	 * @param date
	 * @return
	 */
	public static Date removeTime(Date date) {		
		if (date == null) {
			return null;
		}

		// Obtain an instance of the Calendar.
		Calendar calendar = getCalendar(date);

		// Mark no automatic correction
		calendar.setLenient(false);

		// Remove the hours, minutes, seconds and milliseconds.
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);

		// Return the date again.
		return calendar.getTime();
	}

And not only to build a new Date object, you can use the following methods to adjust date, like get the previous date or get the next date or get yesterday or get tomorrow date

/**
	 * Adjust date, eg to reduce 10 days from date: adjustDate(date,
	 * Calendar.DAY_OF_YEAR, -10);
	 * 
	 * @param date
	 * @param type
	 * @param amount
	 * @return
	 */
	public static Date adjustDate(Date date, int type, int amount) {
		Calendar calendar = getCalendar(date);
		calendar.add(type, amount);
		return calendar.getTime();
	}

	/**
	 * Get the date before, eg: yesterday
	 * 
	 * @param date
	 * @return
	 */
	public static Date getTheDateBefore(Date date) {
		return adjustDate(date, Calendar.DAY_OF_YEAR, -1);
	}

	/**
	 * Get the date after, eg: tomorrow
	 * 
	 * @param date
	 * @return
	 */
	public static Date getTheDateAfter(Date date) {
		return adjustDate(date, Calendar.DAY_OF_YEAR, -1);
	}

Now if you need to compare difference between two dates or time, these methods are for those purpose:

/**
	 * Get time different in millisecond.
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long getTimeDiffInMillis(Date date1, Date date2) {
		Calendar gc1 = getCalendar(date1);
		Calendar gc2 = getCalendar(date2);

		return gc2.getTimeInMillis() - gc1.getTimeInMillis();
	}

	/**
	 * Get Day Different between 2 days.
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int getDaysDiff(Date date1, Date date2) {
		Calendar gc1 = getCalendar();
		Calendar gc2 = getCalendar();

		if (date1.before(date2)) {
			gc1.setTime(date1);
			gc2.setTime(date2);
		}

		else {
			gc1.setTime(date2);
			gc2.setTime(date1);
		}

		gc1.clear(Calendar.MILLISECOND);
		gc1.clear(Calendar.SECOND);
		gc1.clear(Calendar.MINUTE);
		gc1.clear(Calendar.HOUR_OF_DAY);

		gc2.clear(Calendar.MILLISECOND);
		gc2.clear(Calendar.SECOND);
		gc2.clear(Calendar.MINUTE);
		gc2.clear(Calendar.HOUR_OF_DAY);

		int daysDiff = 0;
		while (gc1.before(gc2)) {
			gc1.add(Calendar.DATE, 1);
			daysDiff++;
		}
		return daysDiff;
	}

If you need to compare date only and ignore the time, I mean if 25/09/2011 12:30:45 is the same as 25/09/2011 01:12:14 so you need a compareDateOnly method like this.

/**
	 * Compare date and ignore time
	 * 
	 * @param firstDate
	 * @param secondDate
	 * @return
	 */
	public static int compareDateOnly(Date firstDate, Date secondDate) {

		if (firstDate == null || secondDate == null)
			throw new IllegalArgumentException("The arguments cannot be null");

		Calendar firstCalendar = Calendar.getInstance();
		firstCalendar.setTime(firstDate);

		Calendar secondCalendar = Calendar.getInstance();
		secondCalendar.setTime(secondDate);

		int year = secondCalendar.get(Calendar.YEAR);
		int month = secondCalendar.get(Calendar.MONTH);
		int date = secondCalendar.get(Calendar.DATE);

		secondCalendar.setTime(firstDate);
		secondCalendar.set(Calendar.YEAR, year);
		secondCalendar.set(Calendar.MONTH, month);
		secondCalendar.set(Calendar.DATE, date);

		long oneDayInMillis = 24 * 60 * 60 * 1000L;
		return (int) ((firstCalendar.getTimeInMillis() - secondCalendar.getTimeInMillis()) / oneDayInMillis);
	}

And like above, if you want to compare time of two datetime object and ignore the date part of those parameters, method like below will help

/**
	 * Compare time and ignore date.
	 * 
	 * @param firstTime
	 * @param secondTime
	 * @return
	 */
	public static int compareTimeOnly(Date firstTime, Date secondTime) {

		if (firstTime == null || secondTime == null)
			throw new IllegalArgumentException("The arguments cannot be null");

		Calendar firstCalendar = Calendar.getInstance();
		firstCalendar.setTime(firstTime);

		Calendar secondCalendar = Calendar.getInstance();
		secondCalendar.setTime(secondTime);

		secondCalendar.set(Calendar.YEAR, firstCalendar.get(Calendar.YEAR));
		secondCalendar.set(Calendar.MONTH, firstCalendar.get(Calendar.MONTH));
		secondCalendar.set(Calendar.DATE, firstCalendar.get(Calendar.DATE));

		return (int) ((firstCalendar.getTimeInMillis() - secondCalendar.getTimeInMillis()) / 1000);
	}

How can you check if a date is in range of two other days or to check the old famous leap year? Check out these methods: I have methods to check date in range and time in range..

/**
	 * Check if date is in range of dateFrom and dateTo.
	 * 
	 * @param date
	 * @param dateFrom
	 * @param dateTo
	 * @return
	 */
	public static boolean isDateInRange(Date date, Date dateFrom, Date dateTo) {
		return (date != null && dateFrom != null && (date.equals(dateFrom) || date.equals(dateTo) || (date
				.after(dateFrom) && (dateTo == null || date.before(dateTo)))));
	}

	/**
	 * Check if time is in range of timeFrom and timeTo, ignore date.
	 * 
	 * @param time
	 * @param timeFrom
	 * @param timeTo
	 * @return
	 */
	public static boolean isTimeInRange(Date time, Date timeFrom, Date timeTo) {
		return time != null && timeFrom != null && timeTo != null
				&& CommonDateUtils.compareTimeOnly(timeFrom, time) <= 0
				&& CommonDateUtils.compareTimeOnly(time, timeTo) <= 0;
	}

/**
	 * Check if given year is leap year
	 * 
	 * @param year
	 * @return
	 */
	public static boolean isLeapYear(int year) {
		return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
	}

Previous I introduce you a way to compare if a date is in range of two date object. What to do if you need to compare something bigger? How to get the first moment of a date and the end moment of a date? These method will help you to decide a good range for dates by get the upper bound and lower bound of date for you

/**
	 * Get the beginning moment of the given date.
	 * 
	 * @param date
	 * @return
	 */
	public static Date getLowerBound(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		return calendar.getTime();
	}

	/**
	 * Get the ending moment of the given date.
	 * 
	 * @param date
	 * @return
	 */
	public static Date getUpperBound(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.HOUR_OF_DAY, 23);
		calendar.set(Calendar.MINUTE, 59);
		calendar.set(Calendar.SECOND, 59);
		calendar.set(Calendar.MILLISECOND, 999);
		return calendar.getTime();
	}
/**
	 * Check if given year is leap year
	 * 
	 * @param year
	 * @return
	 */
	public static boolean isLeapYear(int year) {
		return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
	}

Finally, I will add here the complete source of the above demo

package net.searchdaily.java.util.datetime;

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

/**
 * Date Utils by http://java.searchdaily.net.
 * 
 * @author namnvhue
 * 
 */
public class CommonDateUtils {

	public static final SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
	public static final SimpleDateFormat monthYearFormater = new SimpleDateFormat("MM/yyyy");
	public static final SimpleDateFormat timeFormatter = new SimpleDateFormat("hh:mm:ss");
	public static final SimpleDateFormat datetimeFormatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
	public static final SimpleDateFormat datetimeFormatterNoSecond = new SimpleDateFormat("dd/MM/yyyy HH:mm");
	public static final SimpleDateFormat hourMinuteFormater = new SimpleDateFormat("HH:mm");
	public static final SimpleDateFormat timeStampFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

	/**
	 * Delete time from Date.
	 * 
	 * @param date
	 * @return
	 */
	public static Date removeTime(Date date) {
		if (date == null) {
			return null;
		}

		// Obtain an instance of the Calendar.
		Calendar calendar = getCalendar(date);

		// Mark no automatic correction
		calendar.setLenient(false);

		// Remove the hours, minutes, seconds and milliseconds.
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);

		// Return the date again.
		return calendar.getTime();
	}

	/**
	 * Build Date from date/month/year. Zero-based for Month (0=January).
	 * 
	 * @return
	 */
	public static Date buildDate(int year, int month, int date) {
		Calendar calendar = getCalendar();
		calendar.set(year, month, date);
		return calendar.getTime();
	}

	/**
	 * Build Datetime from date/month/year/hour/minute/second. Zero-based for
	 * Month (0=January).
	 * 
	 * @param year
	 * @param month
	 * @param date
	 * @param hour
	 * @param minute
	 * @param second
	 * @return
	 */
	public static Date buildDateTime(int year, int month, int date, int hour, int minute, int second) {
		Calendar calendar = Calendar.getInstance();
		calendar.set(year, month, date, hour, minute, second);
		return calendar.getTime();
	}

	/**
	 * Adjust date, eg to reduce 10 days from date: adjustDate(date,
	 * Calendar.DAY_OF_YEAR, -10);
	 * 
	 * @param date
	 * @param type
	 * @param amount
	 * @return
	 */
	public static Date adjustDate(Date date, int type, int amount) {
		Calendar calendar = getCalendar(date);
		calendar.add(type, amount);
		return calendar.getTime();
	}

	/**
	 * Get the date before, eg: yesterday
	 * 
	 * @param date
	 * @return
	 */
	public static Date getTheDateBefore(Date date) {
		return adjustDate(date, Calendar.DAY_OF_YEAR, -1);
	}

	/**
	 * Get the date after, eg: tomorrow
	 * 
	 * @param date
	 * @return
	 */
	public static Date getTheDateAfter(Date date) {
		return adjustDate(date, Calendar.DAY_OF_YEAR, -1);
	}

	/**
	 * Get time different in millisecond.
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static long getTimeDiffInMillis(Date date1, Date date2) {
		Calendar gc1 = getCalendar(date1);
		Calendar gc2 = getCalendar(date2);

		return gc2.getTimeInMillis() - gc1.getTimeInMillis();
	}

	/**
	 * Get Day Different between 2 days.
	 * 
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int getDaysDiff(Date date1, Date date2) {
		Calendar gc1 = getCalendar();
		Calendar gc2 = getCalendar();

		if (date1.before(date2)) {
			gc1.setTime(date1);
			gc2.setTime(date2);
		}

		else {
			gc1.setTime(date2);
			gc2.setTime(date1);
		}

		gc1.clear(Calendar.MILLISECOND);
		gc1.clear(Calendar.SECOND);
		gc1.clear(Calendar.MINUTE);
		gc1.clear(Calendar.HOUR_OF_DAY);

		gc2.clear(Calendar.MILLISECOND);
		gc2.clear(Calendar.SECOND);
		gc2.clear(Calendar.MINUTE);
		gc2.clear(Calendar.HOUR_OF_DAY);

		int daysDiff = 0;
		while (gc1.before(gc2)) {
			gc1.add(Calendar.DATE, 1);
			daysDiff++;
		}
		return daysDiff;
	}

	/**
	 * Check if given year is leap year
	 * 
	 * @param year
	 * @return
	 */
	public static boolean isLeapYear(int year) {
		return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
	}

	/**
	 * Compare date and ignore time
	 * 
	 * @param firstDate
	 * @param secondDate
	 * @return
	 */
	public static int compareDateOnly(Date firstDate, Date secondDate) {

		if (firstDate == null || secondDate == null)
			throw new IllegalArgumentException("The arguments cannot be null");

		Calendar firstCalendar = Calendar.getInstance();
		firstCalendar.setTime(firstDate);

		Calendar secondCalendar = Calendar.getInstance();
		secondCalendar.setTime(secondDate);

		int year = secondCalendar.get(Calendar.YEAR);
		int month = secondCalendar.get(Calendar.MONTH);
		int date = secondCalendar.get(Calendar.DATE);

		secondCalendar.setTime(firstDate);
		secondCalendar.set(Calendar.YEAR, year);
		secondCalendar.set(Calendar.MONTH, month);
		secondCalendar.set(Calendar.DATE, date);

		long oneDayInMillis = 24 * 60 * 60 * 1000L;
		return (int) ((firstCalendar.getTimeInMillis() - secondCalendar.getTimeInMillis()) / oneDayInMillis);
	}

	/**
	 * Compare time and ignore date.
	 * 
	 * @param firstTime
	 * @param secondTime
	 * @return
	 */
	public static int compareTimeOnly(Date firstTime, Date secondTime) {

		if (firstTime == null || secondTime == null)
			throw new IllegalArgumentException("The arguments cannot be null");

		Calendar firstCalendar = Calendar.getInstance();
		firstCalendar.setTime(firstTime);

		Calendar secondCalendar = Calendar.getInstance();
		secondCalendar.setTime(secondTime);

		secondCalendar.set(Calendar.YEAR, firstCalendar.get(Calendar.YEAR));
		secondCalendar.set(Calendar.MONTH, firstCalendar.get(Calendar.MONTH));
		secondCalendar.set(Calendar.DATE, firstCalendar.get(Calendar.DATE));

		return (int) ((firstCalendar.getTimeInMillis() - secondCalendar.getTimeInMillis()) / 1000);
	}

	/**
	 * Get the beginning moment of the given date.
	 * 
	 * @param date
	 * @return
	 */
	public static Date getLowerBound(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		return calendar.getTime();
	}

	/**
	 * Get the ending moment of the given date.
	 * 
	 * @param date
	 * @return
	 */
	public static Date getUpperBound(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.set(Calendar.HOUR_OF_DAY, 23);
		calendar.set(Calendar.MINUTE, 59);
		calendar.set(Calendar.SECOND, 59);
		calendar.set(Calendar.MILLISECOND, 999);
		return calendar.getTime();
	}

	/**
	 * Check if date is in range of dateFrom and dateTo.
	 * 
	 * @param date
	 * @param dateFrom
	 * @param dateTo
	 * @return
	 */
	public static boolean isDateInRange(Date date, Date dateFrom, Date dateTo) {
		return (date != null && dateFrom != null && (date.equals(dateFrom) || date.equals(dateTo) || (date
				.after(dateFrom) && (dateTo == null || date.before(dateTo)))));
	}

	/**
	 * Check if time is in range of timeFrom and timeTo, ignore date.
	 * 
	 * @param time
	 * @param timeFrom
	 * @param timeTo
	 * @return
	 */
	public static boolean isTimeInRange(Date time, Date timeFrom, Date timeTo) {
		return time != null && timeFrom != null && timeTo != null
				&& CommonDateUtils.compareTimeOnly(timeFrom, time) <= 0
				&& CommonDateUtils.compareTimeOnly(time, timeTo) <= 0;
	}

	public static Calendar getCalendar(Date date) {
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c;
	}

	public static Calendar getCalendar() {
		Calendar c = Calendar.getInstance();
		c.setTime(new Date());
		return c;
	}
}

Hope it helps you, if you have interesting methods for date time calculation please share in the comments. Thanks for reading.

 Leave a Reply

(required)

(required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>