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

Date From Timestamp in Long format

Generally, the dates are stored in long timestamp format in the database.
This simple class can convert the timestamp date to real date format.

package com.kushal.util;
import java.util.Date;
public class DateFromLong {

	public static void main(String ags [])
	{
		long dateInLongFormat=1212499200000L;
		Date date=new Date(dateInLongFormat);

		System.out.println(date);

	}

}

Here is the sample output for the long date give above:

Tue Jun 03 08:20:00 CDT 2008