15

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.

EboMike
  • 76,846
  • 14
  • 164
  • 167
user256239
  • 17,717
  • 26
  • 77
  • 89

6 Answers6

29

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

Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • 1
    Wouldn't it be safe to add `DAY_OF_YEAR` instead `DAY_OF_MONTH`? What if the month is different after adding 5 days? Will `DAY_OF_MONTH` handle that? – ᴛʜᴇᴘᴀᴛᴇʟ Jul 29 '17 at 21:09
  • FYI, the terribly troublesome date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jul 07 '19 at 21:05
18

tl;dr

LocalDate                        // Represent a date-only value, without time-of-day and without time zone.
.now()                           // Capture the current date as seen in the wall-clock time used by the people of a specific region (a time zone). The JVM’s current default time zone is used here. Better to specify explicitly your desired/expected time zone by passing a `ZoneId` argument. Returns a `LocalDate` object.
.with(                           // Generate a new `LocalDate` object based on values of the original but with some adjustment. 
    TemporalAdjusters            // A class that provides some handy pre-defined implementations of `TemporalAdjuster` (note the singular) interface.
    .next(                       // An implementation of `TemporalAdjuster` that jumps to another date on the specified day-of-week.
        DayOfWeek.WEDNESDAY      // Pass one of the seven predefined enum objects, Monday-Sunday.
    )                            // Returns an object implementing `TemporalAdjuster` interface.
)                                // Returns a `LocalDate` object.

Details

Using Java8 Date time API you can easily find the coming Wednesday.

LocalDate nextWed = LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));

next(DayOfWeek dayOfWeek) - Returns the next day-of-week adjuster, which adjusts the date to the first occurrence of the specified day-of-week after the date being adjusted.

Suppose If you want to get previous Wednesday then,

LocalDate prevWed = LocalDate.now().with(TemporalAdjusters.previous(DayOfWeek.WEDNESDAY));

previous(DayOfWeek dayOfWeek) - Returns the previous day-of-week adjuster, which adjusts the date to the first occurrence of the specified day-of-week before the date being adjusted.

Suppose If you want to get next or current Wednesday then

LocalDate nextOrSameWed = LocalDate.now().with(TemporalAdjusters.nextOrSame(DayOfWeek.WEDNESDAY));

nextOrSame(DayOfWeek dayOfWeek) - Returns the next-or-same day-of-week adjuster, which adjusts the date to the first occurrence of the specified day-of-week after the date being adjusted unless it is already on that day in which case the same object is returned.

Edit: You can also pass ZoneId to get the current date from the system clock in the specified time-zone.

ZoneId zoneId = ZoneId.of("UTC");
LocalDate nextWed = LocalDate.now(zoneId).with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));

For more information refer TemporalAdjusters

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Unknown
  • 2,037
  • 3
  • 30
  • 47
4
Calendar c= Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
c.add(Calendar.DAY_OF_MONTH, 7);
c.getTime();
Utsav Gupta
  • 3,785
  • 5
  • 30
  • 52
  • FYI, the terribly troublesome date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jul 07 '19 at 21:11
4

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
  • 90,445
  • 31
  • 189
  • 263
  • FYI, the [*Joda-Time*](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advising migration to the [*java.time*](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jul 07 '19 at 21:11
3

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
  • 76,846
  • 14
  • 164
  • 167
  • 1
    Update: This `Calendar` class is now legacy, supplanted by `java.time.ZonedDateTime` class. And not appropriate to this problem, where `LocalDate` should be used in modern Java. – Basil Bourque Jul 07 '19 at 21:12
0
public static void nextWednesday() throws ParseException 
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        int weekday = calendar.get(Calendar.DAY_OF_WEEK);
        int days = Calendar.WEDNESDAY - weekday;
        if (days < 0)
        {
            days += 7;
        }
        calendar.add(Calendar.DAY_OF_YEAR, days);

        System.out.println(sdf.format(calendar.getTime()));
    }
Soubhab Pathak
  • 619
  • 7
  • 14
  • FYI, the terribly troublesome date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Jul 07 '19 at 21:04
  • You are using a date-with-time type to represent a date-only; square peg, round hole. Also, you are ignoring the crucial issue of time zone, so your results will vary. – Basil Bourque Jul 07 '19 at 21:05
  • For the modern solution using `LocalDate`, see [this Answer](https://stackoverflow.com/a/38569659/642706). – Basil Bourque Jul 07 '19 at 21:13