检查两个日历对象是否在Java中表示相同的本地时间
使用==运算符比较两个日历对象。
让我们首先创建第一个日历对象并设置日期-
Calendar date1 = Calendar.getInstance(); date1.set(Calendar.YEAR, 2040); date1.set(Calendar.MONTH, 10); date1.set(Calendar.DATE, 25); date1.set(Calendar.HOUR_OF_DAY, 11); date1.set(Calendar.MINUTE, 30); date1.set(Calendar.SECOND, 10);
现在,以下是第二个日历对象-
Calendar date2 = Calendar.getInstance(); date2.set(Calendar.YEAR, 2040); date2.set(Calendar.MONTH, 10); date2.set(Calendar.DATE, 25); date2.set(Calendar.HOUR_OF_DAY, 11); date2.set(Calendar.MINUTE, 30); date2.set(Calendar.SECOND, 10);
现在让我们使用==和&&运算符比较它们-
if(date1.get(Calendar.SECOND) == date2.get(Calendar.SECOND) && date1.get(Calendar.MINUTE) == date2.get(Calendar.MINUTE) && date1.get(Calendar.HOUR) == date2.get(Calendar.HOUR) && date1.get(Calendar.DAY_OF_YEAR) == date2.get(Calendar.DAY_OF_YEAR) && date1.get(Calendar.YEAR) == date2.get(Calendar.YEAR) ) { System.out.println("The local time for the calendar objects is same..."); } else { System.out.println("The local time for the calendar objects are different..."); }
以下是最终示例-
示例
import java.util.Calendar; import java.util.GregorianCalendar; public class Demo { public static void main(String[] argv) throws Exception { Calendar date1 = Calendar.getInstance(); date1.set(Calendar.YEAR, 2040); date1.set(Calendar.MONTH, 10); date1.set(Calendar.DATE, 25); date1.set(Calendar.HOUR_OF_DAY, 11); date1.set(Calendar.MINUTE, 30); date1.set(Calendar.SECOND, 10); java.util.Date dt1 = date1.getTime(); System.out.println("Date One = "+dt1); Calendar date2 = Calendar.getInstance(); date2.set(Calendar.YEAR, 2040); date2.set(Calendar.MONTH, 10); date2.set(Calendar.DATE, 25); date2.set(Calendar.HOUR_OF_DAY, 11); date2.set(Calendar.MINUTE, 30); date2.set(Calendar.SECOND, 10); java.util.Date dt2 = date2.getTime(); System.out.println("Date two = "+dt2); if(date1.get(Calendar.SECOND) == date2.get(Calendar.SECOND) && date1.get(Calendar.MINUTE) == date2.get(Calendar.MINUTE) && date1.get(Calendar.HOUR) == date2.get(Calendar.HOUR) && date1.get(Calendar.DAY_OF_YEAR) == date2.get(Calendar.DAY_OF_YEAR) && date1.get(Calendar.YEAR) == date2.get(Calendar.YEAR) ) { System.out.println("The local time for the calendar objects is same..."); } else { System.out.println("The local time for the calendar objects are different..."); } } }
输出结果
Date One = Sun Nov 25 11:30:10 UTC 2040 Date two = Sun Nov 25 11:30:10 UTC 2040 The local time for the calendar objects is same...