Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the most efficient way to strip out the time from a Java Date object?

Tags:

java

date

What's the most efficient way to remove the time portion from a Java date object using only Classes from within the JDK?

I have the following

myObject.getDate() = {java.util.Date}"Wed May 26 23:59:00 BST 2010"

To reset the time back to 00:00:00, I'm doing the following

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date myDate = sdf.parse(sdf.format(myObject.getDate()));

The output is now

myDate = {java.util.Date}"Wed May 26 00:00:00 BST 2010"

Is there a better way to achieve the same result?

like image 278
Pram Avatar asked Dec 02 '22 05:12

Pram


1 Answers

More verbose, but probably more efficient:

    Calendar cal = GregorianCalendar.getInstance();
    cal.setTime(date);
    // cal.set(Calendar.HOUR, 0);   // As jarnbjo pointed out this isn't enough
    cal.set(Calendar.HOUR_OF_DAY, 0);
    cal.set(Calendar.MINUTE, 0);
    cal.set(Calendar.SECOND, 0);
    cal.set(Calendar.MILLISECOND, 0);

Also, you don't need to worry about locale settings, which may cause problems with string to date conversions.

like image 171
kgiannakakis Avatar answered Dec 04 '22 11:12

kgiannakakis