Removing time from a Date object?

You can remove the time part from java.util.Date by setting the hour, minute, second and millisecond values to zero.

import java.util.Calendar;
import java.util.Date;

public class DateUtil {

    public static Date removeTime(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

}

The quick answer is :

No, you are not allowed to do that. Because that is what Date use for.

From javadoc of Date :

The class Date represents a specific instant in time, with millisecond precision.

However, since this class is simply a data object. It dose not care about how we describe it. When we see a date 2012/01/01 12:05:10.321, we can say it is 2012/01/01, this is what you need. There are many ways to do this.

Example 1 : by manipulating string

Input string : 2012/01/20 12:05:10.321

Desired output string : 2012/01/20

Since the yyyy/MM/dd are exactly what we need, we can simply manipulate the string to get the result.

String input = "2012/01/20 12:05:10.321";
String output = input.substring(0, 10);  // Output : 2012/01/20

Example 2 : by SimpleDateFormat

Input string : 2012/01/20 12:05:10.321

Desired output string : 01/20/2012

In this case we want a different format.

String input = "2012/01/20 12:05:10.321";
DateFormat inputFormatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = inputFormatter.parse(input);

DateFormat outputFormatter = new SimpleDateFormat("MM/dd/yyyy");
String output = outputFormatter.format(date); // Output : 01/20/2012

For usage of SimpleDateFormat, check SimpleDateFormat JavaDoc.


What about this:

    Date today = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

    today = sdf.parse(sdf.format(today));

Apache Commons DateUtils has a "truncate" method that I just used to do this and I think it will meet your needs. It's really easy to use:

DateUtils.truncate(dateYouWantToTruncate, Calendar.DAY_OF_MONTH);

DateUtils also has a host of other cool utilities like "isSameDay()" and the like. Check it out it! It might make things easier for you.