2013-07-29 51 views
4

我正在用Java编写程序,我需要确定某个日期是否是周末。但是,我需要考虑到,在不同的国家,周末的不同日子会有不同的日子。在以色列,星期五和星期六是一些伊斯兰国家的周四和周五。欲了解更多详情,你可以检查出this Wikipedia article。有没有简单的方法来做到这一点?如何检查某个日期是否考虑到Java中的当前语言环境是否是周末?

+0

在我看来,这似乎不是我信息存储在一个语言环境中。 –

+0

你应该真的考虑转换到JodaTime而不是使用Java的日期/时间的东西。 (除非你使用的是Java 8,并且不需要支持以前的Java框架--JodaTime或多或少地内置于Java 8中,名称不同。) – RenniePet

+0

@RenniePet是[Joda-Time](http ://www.joda.org/joda-time/)是一个很棒的图书馆。但我不明白它对这个问题有什么帮助。据我所知,Joda-Time不包括周末与周末相关的任何区域信息。 Joda-Time确实支持[ISO 8601](http://en.wikipedia.org/wiki/ISO_8601)标准周,但不支持其他文化周。如果您有一些可以分享的见解或示例代码,请发布答案。 –

回答

0

Java Calendar类具有此功能,getFirstDayOfWeek method。从Calendar文档引用:一周的第一天,在第一周的最少天数(从1到7):

日历使用两个参数定义了一个特定于区域的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 
+6

根据这一点,它是en_US的星期天。这里有个大缺陷:'getFirstDayOfWeek'返回通常是打印日历上的第一天,而不是工作周的第一天。 http://ideone.com/zX4Pcc – zapl

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