java.time
Use LocalDate#with(TemporalAdjuster)
to get the required LocalDate
.
Demo:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MMMM", Locale.ENGLISH);
System.out.println(getNextOrSameDate(DayOfWeek.SUNDAY).format(dtf));
System.out.println(getNextOrSameDate(DayOfWeek.MONDAY).format(dtf));
System.out.println(getNextOrSameDate(DayOfWeek.TUESDAY).format(dtf));
}
static LocalDate getNextOrSameDate(DayOfWeek dw) {
return LocalDate.now().with(TemporalAdjusters.nextOrSame(dw));
}
}
Output:
06 June
07 June
08 June
ONLINE DEMO
Alternatively, you can return the weekday name directly from the function.
Demo:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(getNextOrSameWeekDayName(DayOfWeek.SUNDAY));
System.out.println(getNextOrSameWeekDayName(DayOfWeek.MONDAY));
System.out.println(getNextOrSameWeekDayName(DayOfWeek.TUESDAY));
}
static String getNextOrSameWeekDayName(DayOfWeek dw) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MMMM", Locale.ENGLISH);
return LocalDate.now().with(TemporalAdjusters.nextOrSame(dw)).format(dtf);
}
}
ONLINE DEMO
Alternatively, you can pass the weekday name as String
and return any of the things as shown above. However, this is error-prone and I recommend you pass an enum
instead of a String
as shown in previous examples.
Demo:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Test
System.out.println(getNextOrSameWeekDayName("Sunday"));
System.out.println(getNextOrSameWeekDayName("Monday"));
System.out.println(getNextOrSameWeekDayName("Tuesday"));
}
static String getNextOrSameWeekDayName(String dw) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd MMMM", Locale.ENGLISH);
return LocalDate.now()
.with(TemporalAdjusters.nextOrSame(DayOfWeek.valueOf(dw.toUpperCase())))
.format(dtf);
}
}
ONLINE DEMO
Learn more about java.time
, the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.