使用 Java Calendar 的 before() 方法比较日期时间
Calendar.before() 方法返回此 Calendar 的时间是否早于指定的对象所表示的时间。
首先,我们设置一个在过去的时间(过去时间)
Calendar beforeDate = Calendar.getInstance(); beforeDate.set(Calendar.YEAR, 2010); beforeDate.set(Calendar.MONTH, 05); beforeDate.set(Calendar.DATE, 30);
以下是我们的日期,11-22-2018
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
广告