Removing Time Portion From A Date In Java And Setting Custom Time To A Date

More often developers come across some situations where they need to manipulate the date or time and sometimes the manipulations are kind of tricky. For instance, when you create a new date, you get a time stamp. But you don’t need the time, you just need the date that starts at midnight. In another scenario, you get a date, but you want the end of the day time for example. The new date you get by doing new Date() or Calendar.getInstance() contains the current time, so you either want to remove the time, or set the time to some other times based on what you are trying to accomplish.

In this tutorial, I will show you two things:

  • How to remove the time portion from the date, setting the time to ’00:00:00 000′
  • How to set the custom time to a date which is not current time – for example ’09:40:56 350′

As you can see in the example below, the time manipulation is done by extracting the individual component of the Date object – you extract Hour of Day, Minute, Second, Milliseconds and set them to whatever your need is.

package com.kushal.tools;
/**
 * @author Kushal Paudyal
 * www.sanjaal.com/java
 * www.icodejava.com
 *
 * Create on: 2012-12-26
 * Last Modified On: 2012-12-26
 */
import java.util.Calendar;
import java.util.Date;

public class TimeAdderRemover {

    public static void main(String args[]) {

        Date today = new Date();
        System.out.println("Curent Date & Time: " + today);

        today = removeTimeFromDate(today);
        System.out.println("After Removing Time: " + today);

        today = addTimeToDate(today, 9, 40, 56, 345);
        System.out.println("After Adding Time: " + today);

    }

    public static Date removeTimeFromDate(Date date) {

        if (date == null) {
            return null;
        }
        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();
    }

    public static Date addTimeToDate(Date date, int hourOfDay, int minute, int second, int millisecond) {

        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, second);
        calendar.set(Calendar.MILLISECOND, millisecond);
        return calendar.getTime();
    }

}


Here is the output of this program. Since the output is date and time dependent, it will be different when (and everytime) you run it at your machine.

Curent Date & Time: Wed Dec 26 11:44:17 CST 2012
After Removing Time: Wed Dec 26 00:00:00 CST 2012
After Adding Time: Wed Dec 26 09:40:56 CST 2012

Creating java.util.date and java.util.sql objects from Calendar object

Date, time and calendar manipulation always seem to trouble average developers. Well it does for me too, sometimes. In this particular very simple tutorial, I have shown how we can create java.sql.date object and java.util.date object from Calendar object.

package com.kushal.utils.date;
import java.util.Calendar;

public class DateUsingCalendar {
	/**
	 * @param year - an integer representing the year
	 * @param month - an integer from 0-11 (Jan - Dec)
	 * @param dayOfMonth - an integer from 1-31
	 */
	public static void createDateFromCalendar(int year, int month,
			int dayOfMonth) {

		/**
		 * Creates a current calendar using
		 * the default time zone and locale.
		 */
		Calendar myCalendar = Calendar.getInstance();

		/**
		 * Resets all the attributes of calendar
		 */
		myCalendar.clear();

		/**
		 * Let's try setting our values
		 */
		myCalendar.set(Calendar.YEAR, year);
		myCalendar.set(Calendar.MONTH, month);
		myCalendar.set(Calendar.DATE, dayOfMonth);

		/**
		 * We will try creating a new sqlDate using this
		 * Calendar Object
		 */
		java.sql.Date sqlDateObj = new java.sql.Date(
				myCalendar.getTimeInMillis());

		/**
		 * We will try creating a new java util Date object
		 * using this Calendar Object
		 */
		java.util.Date utilDateObj = myCalendar.getTime();

		/**
		 * Let's try printing these dates to the console
		 */

		System.out.println("Date in sql date format: "+sqlDateObj);
		System.out.println("Date in util date format: "+utilDateObj);

	}

	public static void main(String[] args) {
		int year=2009;
		int month=5; //June (January being 0)
		int dayOfMonth=11;
		createDateFromCalendar(year, month, dayOfMonth);
	}
}


_______________________
Here is the output:
Date in sql date format: 2009-06-11
Date in util date format: Thu Jun 11 00:00:00 CDT 2009

How to calculate age in Java from birthdate?

Playing around with dates is tricky and can sometimes make you use your head, specially with the boundary conditions. In this tutorial, I am presenting a code that can take any birth date as the input and then calculates what is his / her age now.

Here is the algorithm:

  • Subtract birth year from current year.
  • Check if birth month is greater than current month (condition 1)
  • If birth month is same, check if birth day of the month is latter than the current day of the month (condition 2)
  • If condition 1 or condition 2 is satisfied, subtract 1 year from the difference calculated in step 1.
  • This value is the correct age of the individual.

Having said that, here is the Java implementation of this algorithm.

package com.kushal.utils.date;

/**
 * @Author Kushal Paudyal
 * www.sanjaal.com/java
 * Last Modified On 2009-10-13
 *
 * Takes any birth date as input
 * Calculates the current age
 */
import java.util.GregorianCalendar;
import java.util.Calendar;

public class AgeCalculation {

/**
* Month Representations
*/
static final int JAN = 0;
static final int FEB = 1;
static final int MAR = 2;
static final int APR = 3;
static final int MAY = 4;
static final int JUN = 5;
static final int JUL = 6;
static final int AUG = 7;
static final int SEP = 8;
static final int OCT = 9;
static final int NOV = 10;
static final int DEC = 11;

public static void main(String[] args) {
System.out.println("Born In 1982-JUL-11. Current Age: "
+ calculateMyAge(1982, JUL, 11));
System.out.println("Born In 1957-DEC-09. Current Age: "
+ calculateMyAge(1957, DEC, 9));
}

/**
*
* @param year --> Birth Year
* @param month --> Birth Month
* @param day --> Birth Day
* @return --> Calculated Age
*/
private static int calculateMyAge(int year, int month, int day) {
Calendar birthCal = new GregorianCalendar(year, month, day);

Calendar nowCal = new GregorianCalendar();

int age = nowCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);

boolean isMonthGreater = birthCal.get(Calendar.MONTH) >= nowCal
.get(Calendar.MONTH);

boolean isMonthSameButDayGreater = birthCal.get(Calendar.MONTH) == nowCal
.get(Calendar.MONTH)
&& birthCal.get(Calendar.DAY_OF_MONTH) > nowCal
.get(Calendar.DAY_OF_MONTH);

if (isMonthGreater || isMonthSameButDayGreater) {
age=age-1;
}
return age;
}
/*
* SANJAAL CORPS 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. SANJAAL CORPS SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*
* THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
* CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
* PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
* NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
* SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
* SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
* PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES"). SANJAAL CORPS
* SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
* HIGH RISK ACTIVITIES.
*/
}

Here is the output of the program above:

Born In 1982-JUL-11. Current Age: 27
Born In 1957-DEC-09. Current Age: 51