InterviewSolution
Saved Bookmarks
| 1. |
Compare two dates in Java |
|
Answer» Two dates in Java can be compared using the compareTo() method. The syntax for this is given as follows: date1.compareTo(date2)This method returns 0 if both the dates are equal, it returns a value greater than 0 if date1 is after date2 and it returns a value less than 0 if date1 is before date2. A PROGRAM that compares two dates in Java is given as follows: import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class Demo { public static void main(String[] args) THROWS ParseException { SimpleDateFormat dformat = NEW SimpleDateFormat("yyyy-MM-dd"); Date D1 = dformat.parse("2018-12-05"); Date d2 = dformat.parse("2018-08-07"); System.out.println("The date 1 is: " + dformat.format(d1)); System.out.println("The date 2 is: " + dformat.format(d2)); if (d1.compareTo(d2) > 0) { System.out.println("Date 1 occurs after Date 2"); } else if (d1.compareTo(d2) < 0) { System.out.println("Date 1 occurs before Date 2"); } else if (d1.compareTo(d2) == 0) { System.out.println("Both the dates are equal"); } } }The output of the above program is as follows: The date 1 is: 2018-12-05 The date 2 is: 2018-08-07 Date 1 occurs after Date 2 |
|