views:

74

answers:

3

Is there a good way to get the date of the coming Wednesday? That is, if today is Tuesday, I want to get the date of Wednesday in this week; if today is Wednesday, I want to get the date of next Wednesday; if today is Thursday, I want to get the date of Wednesday in the following week.

Thanks.

+2  A: 

Use java.util.Calendar. You get the current date/time like this:

Calendar date = Calendar.getInstance();

From there, get date.get(Calendar.DAY_OF_WEEK) to get the current day of week and get the difference to Calendar.WEDNESDAY and add it.

EboMike
+1; I provided complete snippet in my answer.
polygenelubricants
A: 

Using JodaTime:

    LocalDate date = new LocalDate(System.currentTimeMillis());
    Period period = Period.fieldDifference(date, date.withDayOfWeek(DateTimeConstants.WEDNESDAY));
    int days = period.getDays();
    if (days < 1) {
        days = days + 7;
    }
    System.out.println(date.plusDays(days));
Yishai
+1  A: 

The basic algorithm is the following:

  • Get the current date
  • Get its day of week
  • Find its difference with Wednesday
  • If the difference is not positive, add 7 (i.e. insist on next coming/future date)
  • Add the difference

Here's a snippet to show how to do this with java.util.Calendar:

import java.util.Calendar;

public class NextWednesday {
    public static Calendar nextDayOfWeek(int dow) {
        Calendar date = Calendar.getInstance();
        int diff = dow - date.get(Calendar.DAY_OF_WEEK);
        if (!(diff > 0)) {
            diff += 7;
        }
        date.add(Calendar.DAY_OF_MONTH, diff);
        return date;
    }
    public static void main(String[] args) {
        System.out.printf(
            "%ta, %<tb %<te, %<tY",
            nextDayOfWeek(Calendar.WEDNESDAY)
        );
    }
}

Relative to my here and now, the output of the above snippet is "Wed, Aug 18, 2010".

API links

polygenelubricants