Reputation: 808
Java Q: On any given day, I want to determine the date on which (say) last Friday fell. Example: If I run my program today (ie. Wednesday, 05th Sep 12), I should get the result as "Last Friday was on 31st Aug 12". If I run it on Saturday, 08th Sep 12, the result should be 07th Sep 12, and so on (The date formatting is not strictly an issue here though)
Is there any available api, or do I need to write a program at length going back that many days based on the current day, etc?
Thank you!
Upvotes: 0
Views: 331
Reputation: 2095
I recently developed Lamma Date which is particularly designed for this use case:
new Date(2014, 7, 1).previous(DayOfWeek.FRIDAY); // 2014-06-27
new Date(2014, 7, 2).previous(DayOfWeek.FRIDAY); // 2014-06-27
new Date(2014, 7, 3).previous(DayOfWeek.FRIDAY); // 2014-06-27
new Date(2014, 7, 4).previous(DayOfWeek.FRIDAY); // 2014-06-27
new Date(2014, 7, 5).previous(DayOfWeek.FRIDAY); // 2014-07-04
new Date(2014, 7, 6).previous(DayOfWeek.FRIDAY); // 2014-07-04
new Date(2014, 7, 7).previous(DayOfWeek.FRIDAY); // 2014-07-04
Upvotes: 0
Reputation: 808
int day = cal.get(Calendar.DAY_OF_WEEK);
int dayDiff = (day+1)%7;
if(dayDiff == 0)
dayDiff = 7;
cal.add(Calendar.DAY_OF_MONTH, - dayDiff);
Upvotes: 0
Reputation: 20264
How about this:
Calendar cal = Calendar.getInstance();
int day = cal.get(Calendar.DAY_OF_WEEK);
cal.add(Calendar.DAY_OF_MONTH, -((day + 1) % 7));
Date lastFriday = cal.getTime();
We can always go back to the previous Friday by subtracting the Calendar.DAY_OF_WEEK value for the current date, plus 1. For example, if the current day is Monday (value=2) and we subtract (2 + 1) we go back 3 days to Friday. If we do the same thing on a Tuesday we go back (3 + 1) days - also to a Friday.
If the current day is either Friday or Saturday we need to be sure that we only go back 0 or 1 day respectively, so we just take mod 7 of the (day + 1)
value.
Upvotes: 3