import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date;
public class DateWeekUtil { /** * 根据日期字符串判断当月第几周 */ public static int getWeekOfMonth(String datestr , String format) throws Exception { // 将字符串格式化 SimpleDateFormat sdf = new SimpleDateFormat(format); Date date = sdf.parse(datestr); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); //第几周 int week = calendar.get(Calendar.WEEK_OF_MONTH); //第几天,从周日开始 int day = calendar.get(Calendar.DAY_OF_WEEK); return week; } /** * 根据日期字符串判断当年第几周 */ public static int getWeekOfYear(String datestr , String format) throws Exception { // 将字符串格式化 SimpleDateFormat sdf = new SimpleDateFormat(format); Date d = sdf.parse(datestr); Calendar calendar = Calendar.getInstance(); calendar.setTime(d); // 第几周 return calendar.get(Calendar.WEEK_OF_YEAR); } public static void main(String[] args) throws Exception { Date date = new Date(); String datestr = "2015-05-17" ; String format = "yyyy-MM-dd"; System.out.println("本年第几周:"+getWeekOfYear(datestr, format)); System.out.println("本月第几周:"+getWeekOfMonth(datestr, format)); } }
测试信息: