lang3
Check if Days and Calendars match
With this example we are going to demonstrate how to check if Days and Calendars match. We are using the org.apache.commons.lang3.time.DateUtils
Class, that is a suite of utilities surrounding the use of the Calendar and Date object. DateUtils contains a lot of common methods considering manipulations of Dates or Calendars. In short, to check if Days and Calendars match you should:
- Create two new Date objects.
- Use
isSameDay(Date date1, Date date2)
API method ofDateUtils
to check if the two date objects are on the same day ignoring time. - Then create two new Calendar objects.
- Use
isSameDay(Calendar cal1, Calendar cal2)
API method ofDateUtils
to check if two calendar objects are on the same day ignoring time.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import org.apache.commons.lang3.time.DateUtils; import java.util.Calendar; import java.util.Date; public class CheckDays { public static void main(String[] args) { Date date1 = new Date(); Date date2 = new Date(); System.out.print("Date 1 = " + date1 + " and Date 2 = " +date2); // Check if two instances of Date are the same if (DateUtils.isSameDay(date1, date2)) { System.out.println(" ->Dates match"); } else System.out.println(" ->Dates not match"); Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); System.out.print("Calendar 1 = " + date1 + " and Calendar 2 = " +date2); // Check if two instances of Calendar are the same if (DateUtils.isSameDay(cal1, cal2)) { System.out.println(" ->Calendars match"); } else System.out.println(" ->Calendars not match"); // Change month o the second calendar and test the values cal2.add(Calendar.DAY_OF_MONTH, 10); System.out.print("Calendar 1 = " + date1 + " and Calendar 2 = " +date2); if (DateUtils.isSameDay(cal1, cal2)) { System.out.println(" ->Calendars match"); } else System.out.println(" ->Calendars not match"); } }
Output:
Date 1 = Fri Jul 13 12:52:26 EEST 2012 and Date 2 = Fri Jul 13 12:52:26 EEST 2012 ->Dates match
Calendar 1 = Fri Jul 13 12:52:26 EEST 2012 and Calendar 2 = Fri Jul 13 12:52:26 EEST 2012 ->Calendars match
Calendar 1 = Fri Jul 13 12:52:26 EEST 2012 and Calendar 2 = Fri Jul 13 12:52:26 EEST 2012 ->Calendars don't match
This was an example of how to check if Days and Calendars match in Java.