Set time to 00:00:00
Use another constant instead of Calendar.HOUR
, use Calendar.HOUR_OF_DAY
.
calendar.set(Calendar.HOUR_OF_DAY, 0);
Calendar.HOUR
uses 0-11 (for use with AM/PM), and Calendar.HOUR_OF_DAY
uses 0-23.
To quote the Javadocs:
public static final int HOUR
Field number for get and set indicating the hour of the morning or afternoon. HOUR is used for the 12-hour clock (0 - 11). Noon and midnight are represented by 0, not by 12. E.g., at 10:04:15.250 PM the HOUR is 10.
and
public static final int HOUR_OF_DAY
Field number for get and set indicating the hour of the day. HOUR_OF_DAY is used for the 24-hour clock. E.g., at 10:04:15.250 PM the HOUR_OF_DAY is 22.
Testing ("now" is currently c. 14:55 on July 23, 2013 Pacific Daylight Time):
public class Main
{
static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args)
{
Calendar now = Calendar.getInstance();
now.set(Calendar.HOUR, 0);
now.set(Calendar.MINUTE, 0);
now.set(Calendar.SECOND, 0);
System.out.println(sdf.format(now.getTime()));
now.set(Calendar.HOUR_OF_DAY, 0);
System.out.println(sdf.format(now.getTime()));
}
}
Output:
$ javac Main.java
$ java Main
2013-07-23 12:00:00
2013-07-23 00:00:00
java.time
Using the java.time
framework built into Java 8 and later. See Tutorial.
import java.time.LocalTime;
import java.time.LocalDateTime;
LocalDateTime now = LocalDateTime.now(); # 2015-11-19T19:42:19.224
# start of a day
now.with(LocalTime.MIN); # 2015-11-19T00:00
now.with(LocalTime.MIDNIGHT); # 2015-11-19T00:00
If you do not need time-of-day (hour, minute, second etc. parts) consider using LocalDate
class.
LocalDate.now(); # 2015-11-19
Here are couple of utility functions I use to do just this.
/**
* sets all the time related fields to ZERO!
*
* @param date
*
* @return Date with hours, minutes, seconds and ms set to ZERO!
*/
public static Date zeroTime( final Date date )
{
return DateTimeUtil.setTime( date, 0, 0, 0, 0 );
}
/**
* Set the time of the given Date
*
* @param date
* @param hourOfDay
* @param minute
* @param second
* @param ms
*
* @return new instance of java.util.Date with the time set
*/
public static Date setTime( final Date date, final int hourOfDay, final int minute, final int second, final int ms )
{
final GregorianCalendar gc = new GregorianCalendar();
gc.setTime( date );
gc.set( Calendar.HOUR_OF_DAY, hourOfDay );
gc.set( Calendar.MINUTE, minute );
gc.set( Calendar.SECOND, second );
gc.set( Calendar.MILLISECOND, ms );
return gc.getTime();
}