This tutorial is divided into three sections as follows:
1) Calculate the number of days between two dates
2) Get the previous day date and the next day date from the given date
3) Compare two dates with each other
You’re reading part 3 of above mentioned tutorials: In the below example we are providing the dates in yyyy-MM-dd
format to the custom method(which we have created) and the method is returning the date which is greater than the other one.
import java.text.ParseException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; class CompareExample{ public static void main(String args[]) { CompareExample obj = new CompareExample(); String str= obj.compareTwoDates("2013-11-28", "2013-10-31"); System.out.println(str); } private String compareTwoDates(String fromDate,String toDate) { //split year, month and days from the date using StringBuffer. StringBuffer sBuffer = new StringBuffer(fromDate); String year = sBuffer.substring(2,4); String mon = sBuffer.substring(5,7); String dd = sBuffer.substring(8,10); //split year, month and days from the date using StringBuffer. StringBuffer sBuffer1 = new StringBuffer(toDate); String year1 = sBuffer1.substring(2,4); String mon1 = sBuffer1.substring(5,7); String dd1 = sBuffer1.substring(8,10); String modifiedFromDate = dd +'/'+mon+'/'+year; String modifiedToDate = dd1 +'/'+mon1+'/'+year1; //int MILLIS_IN_DAY = 1000 * 60 * 60 * 24; /* Use SimpleDateFormat to get date in the format as *passed in the constructor. This object can be used to *covert date in string format to java.util.Date and vice versa*/ SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy"); java.util.Date dateSelectedFrom = null; java.util.Date dateSelectedTo = null; // convert date present in the String to java.util.Date. try { dateSelectedFrom = dateFormat.parse(modifiedFromDate); } catch(Exception e) { e.printStackTrace(); } // convert date present in the String to java.util.Date. try { dateSelectedTo = dateFormat.parse(modifiedToDate); } catch(Exception e) { e.printStackTrace(); } //use the compareTo method of java.util.Date to compare two java.util.Dates. if(dateSelectedFrom.compareTo(dateSelectedTo)>0) { return fromDate; } else { return toDate; } } }
Output:
2013-11-28
Leave a Reply