对于日历操作,您必须使用Calendar类。在你的情况,你会做这样的事情:
package test;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
public class TestDate {
public static void main(String[] args) {
Calendar c = new GregorianCalendar();
c.set(Calendar.HOUR_OF_DAY, 12);
c.set(Calendar.MINUTE, 58);
c.set(Calendar.SECOND, 15);
Date d = c.getTime();
System.out.println("Start point: " + d.toString());
System.out.println("Nearest whole minute: " + toNearestWholeMinute(d));
System.out.println("Nearest whole hour: " + toNearestWholeHour(d));
}
static Date toNearestWholeMinute(Date d) {
Calendar c = new GregorianCalendar();
c.setTime(d);
if (c.get(Calendar.SECOND) >= 30)
c.add(Calendar.MINUTE, 1);
c.set(Calendar.SECOND, 0);
return c.getTime();
}
static Date toNearestWholeHour(Date d) {
Calendar c = new GregorianCalendar();
c.setTime(d);
if (c.get(Calendar.MINUTE) >= 30)
c.add(Calendar.HOUR, 1);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
return c.getTime();
}
}
而结果:
Start point: Tue Nov 22 12:58:15 CET 2011
Nearest whole minute: Tue Nov 22 12:58:00 CET 2011
Nearest whole hour: Tue Nov 22 13:00:00 CET 2011