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

Originally posted 2012-12-26 12:23:07.

Share

Calculating Difference In Months For Two Dates

package com.kushal.util;

/**
 * @(#)KpCalendar.java
 * @author Kushal Paudyal (kushalzone@gmail.com)
 * @version 1.00 2007/4/18
 * www.sanjaal.com/java
 */

import java.util.*;

public class KPCalendar {

	/**Default Constructor**/
	public KPCalendar() {
	}

	public double monthDifference(String calString1, String calString2)
	{
		double difference =0;

		try{
			Calendar cal1=new GregorianCalendar();
			Date time1=new Date(calString1);

			cal1.setTime(time1);

			Calendar cal2=new GregorianCalendar();
			Date time2=new Date(calString2);
			cal2.setTime(time2);

			long time1Millis=cal1.getTimeInMillis();
			long time2Millis= cal2.getTimeInMillis();

			double d1=((double)time1Millis)/(1000*60*60*24);
			double d2=((double)time2Millis)/(1000*60*60*24);
			System.out.println(d1);
			System.out.println(d2);

			difference=Math.round(Math.abs((d1-d2)/30));
		}
		catch(Exception e)
		{
			e.printStackTrace();
			System.out.println("Error Occurred");
		}
		finally{
			System.out.println(difference);
			return difference;
		}
	}

	/** Testing for the functionality of the method **/
	public static void main(String args [])
	{
		KPCalendar util=new KPCalendar();
		util.monthDifference("04/01/2007","08/5/2007");
	}
}

Blog Widget by LinkWithin

Originally posted 2007-09-13 15:53:25.

Share