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