我正在尝试获取一个星期的星期数,在我的国家,星期日从星期日开始,因此2016年6月5日的星期数是23但是它返回22因为JAVA的ISO周从星期一,我使用了以下方法,但它不起作用
mCalendar = Calendar.getInstance();
int weekNum = mCalendar.get(Calendar.WEEK_OF_YEAR); //returns 22 I need 23
// I have tried the following method but it has no effect
mCalendar.setFirstDayOfWeek(Calendar.SUNDAY);
请注意,我无法使用时间类,我只能使用Java 7
答案 0 :(得分:1)
Java 8 版本完整答案:
public<T extends Temporal> long getWeekNumber(T tObj) {
DayOfWeek firstDayOfWeek = DayOfWeek.SUNDAY; // set your
Temporal firstDayOfThisYear = tObj.with(TemporalAdjusters.firstDayOfYear());
Temporal firstDayOfWeekInMonth = firstDayOfThisYear
.with(TemporalAdjusters.dayOfWeekInMonth(1, firstDayOfWeek));
return ChronoUnit.WEEKS.between(tObj, firstDayOfWeekInMonth);
}
参数可以是任何 Temporal
类型,甚至是 Temporal
本身。
答案 1 :(得分:0)
我不知道你在哪里,但Java有一个很棒的日历,允许以下内容:
Calendar calendar = Calendar.getInstance(Locale.TRADITIONAL_CHINESE);
int weekNumber = calendar.get(Calendar.WEEK_OF_YEAR);
System.out.println("Number of week: " + weekNumber);
// produces 24
Calendar calendar = Calendar.getInstance(Locale.UK);
int weekNumber = calendar.get(Calendar.WEEK_OF_YEAR);
System.out.println("Number of week: " + weekNumber);
// produces 22
您可以使用区域设置常量来指定您的位置,我认为您将获得正确的周数。
编辑: 现在我看到你的代码失败了。请注意,Java从代码的顶部到按钮起作用:
Calendar calendar = Calendar.getInstance();
// First set the first day of the week ...
calendar.setFirstDayOfWeek(Calendar.SUNDAY);
// ... and than you could ask the calendar for the week
int weekNumber = calendar.get(Calendar.WEEK_OF_YEAR);
// will produce 23
System.out.println("Number of week: " + weekNumber);
答案 2 :(得分:0)
我不知道你来自哪里。 我是法国人,这种方式很有效:
Calendar mCalendar = Calendar.getInstance(Locale.FRANCE);
mCalendar.setFirstDayOfWeek(Calendar.SUNDAY);
int weekNum = mCalendar.get(Calendar.WEEK_OF_YEAR);
System.out.println(weekNum); // --> 23
答案 3 :(得分:0)
答案 4 :(得分:0)
我刚才想出了如何改变它 你需要设置两件事 一周的第一天 2 - 一周中最小的一天
setFirstDayOfWeek(Calendar.SUNDAY);
setMinimalDaysInFirstWeek(7);
这将告诉日历使第一天是星期日和7天最小的一周