WeekUtil.java 与日期有关的操作

从网上找来的一篇仁兄的文章。。。借来引用下。放到了我的lib当中,描述了一些一周之内的日期查询的一些相关code。。


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;


Calendar c = new GregorianCalendar();
c.set(2007, Calendar.FEBRUARY, 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));
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值