日期:2014-05-18  浏览次数:20764 次

Java 应用
向大家请教一个问题
Java web 中 如何判断 一年有多少个周,那天是星期几

------解决方案--------------------
/**
* 得到某一年周的总数

* @param year
* @return
*/
public static int getMaxWeekNumOfYear(int year) { 
Calendar c = new GregorianCalendar();
c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);
if(year==1989||year==1995||year==2006||year==2012||year==2017||year==2023||year==2034) return 53;
else return 52;
//return getWeekOfYear(c.getTime());
}

/**
* 取得当前日期是多少周

* @param date
* @return
*/
public static int getWeekOfYear(Date date) {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setMinimalDaysInFirstWeek(7);
c.setTime (date);

return c.get(Calendar.WEEK_OF_YEAR);
}

/**
* 取得当前日期所在周的第一天

* @param date
* @return
*/
public static Date getFirstDayOfWeek(Date date) { 
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek()); // Monday
return c.getTime ();
}

/**
* 取得当前日期所在周的最后一天

* @param date
* @return
*/
public static Date getLastDayOfWeek(Date date) {
Calendar c = new GregorianCalendar();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6); // Sunday
return c.getTime();
}