需求就是这样,显示一周的日历。
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String number[] = new String[7];
Calendar calendar = Calendar.getInstance();
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String currentDay = dateFormat.format(date);
int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
System.out.println(" currentDayOfWeek = "+currentDayOfWeek);
number[currentDayOfWeek - 1] = currentDay.substring(
currentDay.length() - 2, currentDay.length());
int beforeDayBetween=currentDayOfWeek - 1;
int k=1;
int y=1;
if(beforeDayBetween>0){
for(int i=beforeDayBetween-1;i>=0;i--){
String sTime=getDayOffset(currentDay,-k);
number[i]=sTime.substring(sTime.length()-2, sTime.length());
k++;
}
if(beforeDayBetween<6){
for(int i=currentDayOfWeek;i<=6;i++){
String sTime=getDayOffset(currentDay,y);
number[i]=sTime.substring(sTime.length()-2, sTime.length());
y++;
}
}
}else {
for(int i=0;i<7;i++){
String sTime=getDayOffset(currentDay,i);
number[i]=sTime.substring(sTime.length()-2, sTime.length());
}
}
for(int j=0;j<number.length;j++){
System.out.println(" number[j] = "+number[j]);
}
}
public static String getDayOffset(String sourceDateTime,int dayOffset){
Calendar mCalendar=Calendar.getInstance();
mCalendar.setTime(convertToDate(sourceDateTime));
mCalendar.add(Calendar.DAY_OF_MONTH, dayOffset);
SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
return sf.format(mCalendar.getTime());
}
public static Date convertToDate(String dateStr){
Date mDate=null;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
mDate=dateFormat.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return mDate;
}
}