使用Java日历的before()方法比较日期时间
Calendar.before()方法返回此Calendar的时间是否早于指定Object表示的时间。
首先,让我们设置一个过去的日期(过去的日期)
Calendar beforeDate = Calendar.getInstance(); beforeDate.set(Calendar.YEAR, 2010); beforeDate.set(Calendar.MONTH, 05); beforeDate.set(Calendar.DATE, 30);
这是我们的约会日期,2018年11月22日
Calendar currentDate = Calendar.getInstance();
现在,使用before()
方法比较两个日期,如以下示例所示
示例
import java.util.Calendar; public class Demo { public static void main(String[] args) { Calendar beforeDate = Calendar.getInstance(); beforeDate.set(Calendar.YEAR, 2010); beforeDate.set(Calendar.MONTH, 05); beforeDate.set(Calendar.DATE, 30); java.util.Date dt = beforeDate.getTime(); System.out.println("Past Date = "+dt); Calendar currentDate = Calendar.getInstance(); System.out.println("Current date = " + (currentDate.get(Calendar.MONTH) + 1) + "-" + currentDate.get(Calendar.DATE) + "-" + currentDate.get(Calendar.YEAR)); System.out.println("Date "+dt+ " is before current date? = " + beforeDate.before(currentDate)); } }
输出结果
Past Date = Wed Jun 30 13:14:28 UTC 2010 Current date = 11-22-2018 Date Wed Jun 30 13:14:28 UTC 2010 is before current date? = true