Issue
I am trying to check if a particular date is one week before from today's date. I formatted my date into this format:
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
Then, I get the list of date from a for loop by these code:
Date formattedToday = formatter.parse(todayStr);
Date formattedExpired = formatter.parse(expiredDate);
The example of dates in the list are:
09/12/2017 08:09 PM
10/24/2015 02:09 AM
07/18/2018 03:10 AM
I tried to follow this thread but I am not allowed to add in any external libraries.
The other solution that requires Java 8
is not applicable for me also as my current min API is 25 but ChronoUnit
requires API 26
.
Any ideas? Thanks!
Solution
Using only Date
and Calendar
classes (and thus, compatible with any JVM from about 4-ish, I think?) you could try this sort of solution:
- Get today as a
Date
:Date now = new Date()
- Get one week ago from that, as a
Calendar
:Calendar expected = Calendar.getInstance(); expected.setTime(now); lastWeek.add(Calendar.WEEK_OF_YEAR, -1);
- Get your expired date as a
Calendar
:Calendar actual = Calendar.getInstance().setTime(expiredDate);
- Compare the year and day of year of the two calendars (you can compare other fields, but those two should be enough):
return (expected.get(Calendar.YEAR) == actual.get(Calendar.YEAR)) && (expected.get(Calendar.WEEK_OF_YEAR) == actual.get(Calendar.WEEK_OF_YEAR));
Using this, you should be able to come up with an even shorter snippet that subtracts a week from now and compares the long values of the two. Though obviously that wouldn't be comparing calendar dates, it would be comparing nanoseconds :)
Answered By - Paul Hicks
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.