# 加载中...

yxgyh520
• 博客等级：
• 博客积分：0
• 博客访问：3,751
• 关注人气：0
• 获赠金笔：0支
• 赠出金笔：0支
• 荣誉徽章：

## Java中用Calendar类计算周和周的起始日期

(2008-06-01 15:11:43)

### it

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class WeekUtil {

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

public static int getMaxWeekNumOfYear(int year) {
Calendar c = new GregorianCalendar();
c.set(year, Calendar.DECEMBER, 31, 23, 59, 59);

return getWeekOfYear(c.getTime());
}

public static Date getFirstDayOfWeek(int year, int week) {
Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set (Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE, 1);

Calendar cal = (GregorianCalendar) c.clone();

return getFirstDayOfWeek(cal.getTime ());
}

public static Date getLastDayOfWeek(int year, int week) {
Calendar c = new GregorianCalendar();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, Calendar.JANUARY);
c.set(Calendar.DATE, 1);

Calendar cal = (GregorianCalendar) c.clone();

return getLastDayOfWeek(cal.getTime());
}

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

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

public static void main(String[] args) {
int year = 2006;
int week = 1;

// 以2006-01-02位例
Calendar c = new GregorianCalendar();
c.set(2006, Calendar.JANUARY, 2);
Date d = c.getTime();

System.out.println("current date = " + d);
System.out.println("getWeekOfYear = " + getWeekOfYear(d));
System.out.println("getMaxWeekNumOfYear = " + getMaxWeekNumOfYear(year));
System.out.println("getFirstDayOfWeek = " + getFirstDayOfWeek(year, week));
System.out.println("getLastDayOfWeek = " + getLastDayOfWeek(year, week));
System.out.println ("getFirstDayOfWeek = " + getFirstDayOfWeek(d));
System.out.println("getLastDayOfWeek = " + getLastDayOfWeek(d));
}
}

0

• 评论加载中，请稍候...

发评论

以上网友发言只代表其个人观点，不代表新浪网的观点或立场。

新浪BLOG意见反馈留言板　不良信息反馈　电话：4006900000 提示音后按1键（按当地市话标准计费）　欢迎批评指正

新浪公司 版权所有