加载中…
正文 字体大小:

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

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

时间

calenda

计算周

it

分类: JAVA技术

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();
cal.add(Calendar.DATE, week * 7);

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();
cal.add(Calendar.DATE , week * 7);

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键(按当地市话标准计费) 欢迎批评指正

    新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 会员注册 | 产品答疑

    新浪公司 版权所有