我正在用Java编写一个程序,我需要确定某个日期是否是周末。然而,我需要考虑到,在不同的国家,周末在不同的日子,例如在以色列是星期五和星期六,而在一些伊斯兰国家是星期四和星期五。有关更多详细信息,您可以查看这篇维基百科文章。有简单的方法吗?
基于您发送的wiki,我用以下代码为自己解决了这个问题:
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};
}
}
您可以获得星期几(请参阅:如何通过传递特定日期来确定星期几?)
然后根据选择的国家来检查这一天是否是周末。
Java Calendar
类具有此功能,即getFirstDayOfWeek
方法。引用Calendar
文档:
日历使用两个参数定义特定于区域设置的七天一周:一周的第一天和第一周的最小天数(从1到7)。当构建日历时,这些数字取自区域设置资源数据。它们也可以通过设置其值的方法明确指定。
因此,有了这些信息,你就可以计算一天是否是周末。
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
Jollyday这个库可以用来计算假期,http://jollyday.sourceforge.net/index.html