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!
How about this:
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.