Reputation: 3
I need to get a date range starting last Wednesday to yesterday. This program is run on every Wednesday. Is it the good way to do it? What if the program is run on a Tuesday for some reason? How do I make it work? Thanks.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -7);
Date transactionBeginDate = calendar.getTime();
calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, -1);
Date transactionEndDate = calendar.getTime();
Upvotes: 0
Views: 1459
Reputation: 17826
I would use the DAY_OF_WEEK value on the calendar.
Something like ...
while(calendar.DAY_OF_WEEK != Calendar.WEDNESDAY){
calendar.add(Calendar.DAY_OF_MONTH, -1);
}
Date transactionBeginDate = calendar.getTime();
If you do this on a Thursday you'll end up getting your start and end dates as the same day. You should be able to better tweak it to your liking though.
If you wanted to get a whole week regardless of when the program is run then I think you want to start with your end date and then get your start date...
Calendar calendar = Calendar.getInstance();
//Find last Wednesday to act as end date
while(calendar.DAY_OF_WEEK != Calendar.WEDNESDAY){
calendar.add(Calendar.DAY_OF_MONTH, -1);
}
Date transactionEndDate = calendar.getTime();
//Go back one week from that Wednesday to get start date.
calendar.add(Calendar.DAY_OF_MONTH, -7);
Date transactionStartDate = calendar.getTime();
Upvotes: 2