Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a certain date is a weekend taking into account the current locale in Java?

I'm writing a program in Java and I need to determine whether a certain date is weekend or not. However, I need to take into account that in various countries weekends fall on different days, e.g. in Israel it's Friday and Saturday wheras in some islamic countries it's Thursday and Friday. For more details you can check out this Wikipedia article. Is there a simple way to do it?

like image 533
Bartek Avatar asked Oct 22 '22 04:10

Bartek


1 Answers

Based on the wiki you've sent I've solved it for myself with the following code:

private static final List<String> sunWeekendDaysCountries = Arrays.asList(new String[]{"GQ", "IN", "TH", "UG"});
private static final List<String> fryWeekendDaysCountries = Arrays.asList(new String[]{"DJ", "IR"});
private static final List<String> frySunWeekendDaysCountries = Arrays.asList(new String[]{"BN"});
private static final List<String> thuFryWeekendDaysCountries = Arrays.asList(new String[]{"AF"});
private static final List<String> frySatWeekendDaysCountries = Arrays.asList(new String[]{"AE", "DZ", "BH", "BD", "EG", "IQ", "IL", "JO", "KW", "LY", "MV", "MR", "OM", "PS", "QA", "SA", "SD", "SY", "YE"});

public static int[] getWeekendDays(Locale locale) {
    if (thuFryWeekendDaysCountries.contains(locale.getCountry())) {
        return new int[]{Calendar.THURSDAY, Calendar.FRIDAY};
    }
    else if (frySunWeekendDaysCountries.contains(locale.getCountry())) {
        return new int[]{Calendar.FRIDAY, Calendar.SUNDAY};
    }
    else if (fryWeekendDaysCountries.contains(locale.getCountry())) {
        return new int[]{Calendar.FRIDAY};
    }
    else if (sunWeekendDaysCountries.contains(locale.getCountry())) {
        return new int[]{Calendar.SUNDAY};
    }
    else if (frySatWeekendDaysCountries.contains(locale.getCountry())) {
        return new int[]{Calendar.FRIDAY, Calendar.SATURDAY};
    }
    else {
        return new int[]{Calendar.SATURDAY, Calendar.SUNDAY};
    }
}
like image 177
João Rebelo Avatar answered Oct 26 '22 18:10

João Rebelo