Below accepts the date provided as string, and formatted in the ISO-8601 extended local date format (e.g. 2010-02-16). The day of Week is using the DayOfWeek
Enum. Note however that this depends on Java 8 (standard libraries, not Joda-Time). Use of LocalDate
is important to avoid TimeZone and Time issues (partial days).
UPDATE: also provided a static method mimicking the VB version with an integer parameter for the date. All except 0 (System default based on NLS) are accepted.
UPDATE #2: Had to modify previous
into previousOrSame
otherwise we would get 8 instead of 1 as result. The result is expected to be in the range 1-7.
import java.time.DayOfWeek;
import java.time.LocalDate;
import static java.time.DayOfWeek.*;
import static java.time.temporal.ChronoUnit.*;
import static java.time.temporal.TemporalAdjusters.*;
public class Main {
public static void main(String[] args) {
// Thanks to @Markus for the testcase
System.out.println(getVbWeekday("2010-02-16", 1));
System.out.println(getVbWeekday("2015-05-03", 1));
System.out.println(getVbWeekday("2015-05-04", 1));
System.out.println(getVbWeekday("2015-05-05", 1));
System.out.println(getVbWeekday("2015-05-06", 1));
System.out.println(getVbWeekday("2015-05-07", 1));
System.out.println(getVbWeekday("2015-05-08", 1));
System.out.println(getVbWeekday("2015-05-09", 1));
System.out.println(getVbWeekday("2015-05-10", 1));
}
public static int getWeekdayNumber(String dateAsString,DayOfWeek firstDayOfWeek) {
LocalDate d = LocalDate.parse(dateAsString);
// add 1 because between is exclusive end date.
return (int)DAYS.between(d.with(previousOrSame(firstDayOfWeek)),d)+1;
}
public static int getVbWeekday(String dateAsString,int firstDayOfWeek) {
return getWeekdayNumber(dateAsString,SATURDAY.plus(firstDayOfWeek));
}
}