考虑到Java当前的语言环境,如何检查某个日期是否是一个周末?

时间:2013-07-29 15:19:08

标签: java date datetime dayofweek weekend

我正在用Java编写程序,我需要确定某个日期是否是周末。但是,我需要考虑到,在不同的国家/地区,周末会在不同的日子出现,例如:在以色列,星期四和星期五在一些伊斯兰国家的星期五和星期六。有关详细信息,请查看this Wikipedia article。有一个简单的方法吗?

4 个答案:

答案 0 :(得分:2)

根据您发送的维基,我已使用以下代码为自己解决了这个问题:

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};
    }
}

答案 1 :(得分:0)

您可以获取星期几(请参阅:How to determine day of week by passing specific date?

然后根据选择的国家/地区检查当天是否是周末。

答案 2 :(得分:0)

Java Calendar类具有此功能,getFirstDayOfWeek method。引自Calendar文档:

  

日历使用两个参数定义特定于语言环境的七天工作周:一周的第一天和第一周的最小天数(从1到7)。构建Calendar时,这些数字取自语言环境资源数据。也可以通过设置其值的方法明确指定它们。

因此,通过这些信息,您可以计算出某一天是否是周末。

    final Calendar cal = Calendar.getInstance(new Locale("he_IL"));
    System.out.println("Sunday is the first day of the week in he_IL? " + (Calendar.SUNDAY == cal.getFirstDayOfWeek()));

输出:

Sunday is the first day of the week in he_IL? true

答案 3 :(得分:0)

图书馆 Jollyday 可用于计算假期,http://jollyday.sourceforge.net/index.html