工作中遇到一个问题,就是根据当前日期查询本周的第一天和最后一天,来统计数据。这个工作周,要从周五开始到周四结束。找了找。没找到合适的,就在其他类似的基础上进行了修改。就出现了今天的这个实例。具体实现如下。
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
/**
* @author zhangbingbing
*
*/
public class TestFirstDayOfWeek {
private static int TOTAL_DAYS_OF_WEEK = 7;
//设置一周开始的时间,按照周日=1,周一=2 。。。。周六=7 类推
private static int THE_FIRST_DAY = 6;
/**
* @param args
*/
public static void main(String[] args) {
List<String> weekLists = new ArrayList<String>();
weekLists = getTheWeekList(10);
System.out.println("=========weekLists==============="+weekLists);
String weeksString = weekLists.get(0);
String ksrqString = weeksString.substring(0,10);
String jzrqString = weeksString.substring(12);
System.out.println("=========weeksString==============="+weeksString);
}
/**
*
* @param theNumberOfWeek
* @return
*/
public static List<String> getTheWeekList(int theNumberOfWeek,int theFirstDay){
StringBuffer sbBuffer = new StringBuffer();
String dayString = "";
int weeks=0;
List<String> weekList = new ArrayList<String>();
for (int i =0 ;i<theNumberOfWeek;i++ ){
weeks--;
sbBuffer.append(getFirstday(theFirstDay,weeks)).append("--").append(getLastDay(theFirstDay,weeks));
dayString = sbBuffer.toString();
sbBuffer.setLength(0);
weekList.add(dayString);
}
return weekList;
}
/**
* 要返回需要的过去几周日期列表
* theNumberOfWeek 为返回列表数目
*/
public static List<String> getTheWeekList(int theNumberOfWeek){
StringBuffer sbBuffer = new StringBuffer();
String dayString = "";
List<String> weekList = new ArrayList<String>();
weekList=getTheWeekList(theNumberOfWeek,THE_FIRST_DAY);
return weekList;
}
/**
*
* 获得本工作周的第一天
* 首先定义一个参数firstDay,这个参数取值为1-7之间,总共七个数,分别表示周日至周六星期日是第一天,星期二是第三天......
* 可以设置firstday为一周内的任意一天。
*/
public static int getFirstDayPlus(int firstDay) {
// 首先实例化一个Calendar对象,取得当前日期
Calendar cd = Calendar.getInstance();
// 获得今天是一周的第几天,星期日是第一天,星期二是第三天......
int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
if((TOTAL_DAYS_OF_WEEK-dayOfWeek+firstDay)%7==0){
return TOTAL_DAYS_OF_WEEK;
}
return (TOTAL_DAYS_OF_WEEK-dayOfWeek+firstDay)%7;
}
/**
* 获得相应的工作周的第一天的日期
*
* @return
*/
public static String getFirstday(int theFirstDay,int weeks) {
int firstDayPlus = getFirstDayPlus(theFirstDay);
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, firstDayPlus + 7 * weeks);
Date firstDay = currentDate.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String theDay = format.format(firstDay);
return theDay;
}
/**
* 获得相应周最后一天的日期
*
* @return
*/
public static String getLastDay(int theFirstDay,int weeks) {
int firstDayPlus = getFirstDayPlus(theFirstDay);
GregorianCalendar currentDate = new GregorianCalendar();
currentDate.add(GregorianCalendar.DATE, firstDayPlus + 7 * weeks + 6);
Date lastDay = currentDate.getTime();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String theDay = format.format(lastDay);
return theDay;
}
}