I am trying to check in Java 8 if a date is older than 10 years and newer than 20 years. I am using Date.before()
And Date.after()
and passing currentDate-10
years and currentDate-20
years as arguments.
Can someone please suggest what will the cleanest way to get a date which is 10 year old and 20 years old in Date format to pass it in my before()
and after()
methods?
1. Java 8 isBefore() First minus the current date and then uses isBefore() to check if a date is a certain period older than the current date. 1.1 This example checks if a date is 6 months older than the current date.
In Java, two dates can be compared using the compareTo() method of Comparable interface. 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.
The after() method is used to check if a given date is after another given date. Return Value: true if and only if the instant represented by this Date object is strictly later than the instant represented by when; false otherwise.
The idea is quite simple, just use Calendar class to roll the month back and forward to create a “date range”, and use the Date. before() and Date. after() to check if the Date is within the range.
You can use java.time.LocalDate to do this. Example: If you need to check if 01/01/2005 is between that duration, you can use
LocalDate date = LocalDate.of(2005, 1, 1); // Assign date to check LocalDate today = LocalDate.now(); if (date.isBefore(today.minusYears(10)) && date.isAfter(today.minusYears(20))) { //Do Something }
Using Calendar
you can easily get a 10 year old date and 20 year old date from the current date.
Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.YEAR, -10); Date d1 = calendar.getTime(); calendar.add(Calendar.YEAR, -10); Date d2 = calendar.getTime();
As you are using Java 8 you can also use LocalDate
LocalDate currentDate = LocalDate.now(); Date d1 = Date.from(currentDate.minusYears(10).atStartOfDay(ZoneId.systemDefault()).toInstant()); Date d2 = Date.from(currentDate.minusYears(20).atStartOfDay(ZoneId.systemDefault()).toInstant());
For comparing you can use the date.after()
and date.before()
methods as you said.
if(date.after(d1) && date.before(d2)){ //date is the Date instance that wants to be compared //// }
The before()
and after()
methods are implemented in Calendar
and LocalDate
too. You can use those methods in those instances without converting into java.util.Date
instances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With