14

给定日期,我如何获得一年中的一周?我尝试了以下代码:

  Calendar sDateCalendar = new GregorianCalendar();
  sDateCalendar.set(Integer.parseInt(sDateYearAAAA), Integer.parseInt(sDateMonthMM)-1, Integer.parseInt(sDateDayDD));
  System.out.format("sDateCalendar %tc\n", sDateCalendar);        
  iStartWeek = sDateCalendar.getWeekYear();
  System.out.println("iStartWeek "+iStartWeek+ " "+sDateCalendar.WEEK_OF_YEAR);

我得到: sDateCalendar lun apr 23 11:58:39 CEST 2012 iStartWeek 2012 3

而一年中正确的星期是 17。有人可以帮我吗?

4

4 回答 4

25
于 2016-01-18T01:59:14.740 回答
22

优雅的方式(不需要 java.util.Calendar):

new SimpleDateFormat("w").format(new java.util.Date())
于 2013-09-06T12:00:09.537 回答
20

您正在使用 sDateCalendar.WEEK_OF_YEAR,它是静态整数 WEEK_OF_YEAR,请参阅 java.util.Calendar 类的源代码:

public final static int WEEK_OF_YEAR = 3;

要获得周数,您应该使用:

sDateCalendar.get(Calendar.WEEK_OF_YEAR);
于 2012-04-23T10:06:04.223 回答
1
Calendar calendar = Calendar.getInstance(Locale.WHATEVER);
calendar.set(year, month, day);
calendar.get(Calendar.WEEK_OF_YEAR);

小心日历中的月份,因为它从 0 开始,或者更好地使用 Calendar.WHATEVER_MONTH

于 2021-07-29T19:33:59.463 回答