Sabuj Hassan
Sabuj Hassan

Reputation: 39385

Strange java.util.calendar Output

I am trying to clear the time portion from a Date using Java Calendar. Here is the code based on the other stackoverflow solutions:

Calendar cal = Calendar.getInstance();
// cal.setTime(new Date());
cal.clear(Calendar.HOUR);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
// cal.clear(Calendar.ZONE_OFFSET);
cal.clear(Calendar.HOUR_OF_DAY);

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dateFormat.format(cal.getTime());
System.out.println(dateFormat.format(cal.getTime()));
System.out.println(cal.getTime());

But the current output is: 2014-01-20 12:00:00

What could be the reason? Why the time is showing 12:00:00? I just want my Date Object with a time 00:00:00.

Upvotes: 1

Views: 241

Answers (3)

harsh
harsh

Reputation: 7692

As per javadoc of Calendar.clear:

The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and the the resolution rule for the time of day is applied. Clearing one of the fields doesn't reset the hour of day value of this Calendar. Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.

So instead of clear use:

cal.set(Calendar.HOUR_OF_DAY, 0)

clear isn't actually clearing hour value, hence so much messing around formatters!

Upvotes: 2

Prabhakaran Ramaswamy
Prabhakaran Ramaswamy

Reputation: 26094

Do like this

    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);


    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    dateFormat.format(cal.getTime());
    System.out.println(dateFormat.format(cal.getTime()));
    System.out.println(cal.getTime());

Upvotes: 0

Peter Walser
Peter Walser

Reputation: 15706

The date/calendar is ok, the error is in your format string:

  • hh: means 12h time format
  • HH: means 24h time format

Correct format string:

yyyy-MM-dd HH:mm:ss

Output:

2014-01-20 00:00:00
Mon Jan 20 00:00:00 CET 2014

Upvotes: 4

Related Questions