This example will demonstrate how to truncate the time elements from a date while using java SimpleDateFormat, Joda formatdate and Apache’s DateUtils.truncate.
Straight up Java
@Test
public void truncate_time_in_java () {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
// format object
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
String randomTruncatedDateFormatted = dateFormatter.format(cal.getTimeInMillis());
logger.info("Truncated date: " + randomTruncatedDateFormatted);
assertTrue(randomTruncatedDateFormatted.contains("12:00:00"));
}
Output
Truncated date: 10/14/2013 12:00:00
Joda Time
@Test
public void truncate_time_in_java_with_joda () {
DateTime dt = new DateTime().dayOfMonth().roundFloorCopy();
// just for formatting purposes
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
String randomTruncatedDateFormatted = dateFormatter.format(dt.getMillis());
logger.info("Truncated date: " + randomTruncatedDateFormatted);
assertTrue(randomTruncatedDateFormatted.contains("12:00:00"));
}
Output
Truncated date: 10/14/2013 12:00:00
Apache Commons
@Test
public void truncate_time_in_java_with_apache_commons () {
Calendar cal = Calendar.getInstance();
Date someRandomTruncatedDate = DateUtils.truncate(cal.getTime(), Calendar.DATE);
// format object
SimpleDateFormat dateFormatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss z");
String randomTruncatedDateFormatted = dateFormatter.format(someRandomTruncatedDate);
logger.info("Truncated date: " + randomTruncatedDateFormatted);
assertTrue(randomTruncatedDateFormatted.contains("12:00:00"));
}
Output
Truncated date: 10/14/2013 12:00:00 CDT