Milli Saboski
Milli Saboski

Reputation: 3

Getting a Specific Date Range

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

Answers (2)

Shaded
Shaded

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.

edit

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

Hank Gay
Hank Gay

Reputation: 71939

You may want to look at the Interval feature of Joda-Time. If you need to use dates in Java, you should just bite the bullet and learn Joda-Time now. It will save you a ton of headache later.

Upvotes: 2

Related Questions