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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With