一、使用Calendar 中的before 和after方法比较。
日期1.before(日期2),第一个日期在第二个日期之前的意思。
日期1.after(日期2),第一个日期在第二个日期之后的意思。
测试1:
public static void main(String args[]) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse("2021-01-29 14:45:00"));
Calendar now = Calendar.getInstance();
System.out.println(sdf.format(now.getTime()));
System.out.println(sdf.format(calendar.getTimeInMillis()));
System.out.println(calendar.before(now));
}
结果如下
测试2:
public static void main(String args[]) throws Exception{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse("2021-01-29 14:45:00"));
Calendar now = Calendar.getInstance();
System.out.println(sdf.format(now.getTime()));
System.out.println(sdf.format(calendar.getTimeInMillis()));
System.out.println(calendar.after(now));
}
结果如下
二、Calendar 中日期的加减
Calendar对象中的add方法,可以对日期进行加减,add中需要两个参数,第一个参数为类型,可选参数为年,月,日,时,分,秒等。第二个为数值,传入正数即为加,传入负数即为减。
测试如下