public static void main(String[] args) {
SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
try {
// 开始时间
Date beginDate = format.parse("2017-08-23");
// 结束时间
Date endDate = format.parse("2017-08-25");
long day = (endDate.getTime() - beginDate.getTime()) / (24 * 60 * 60 * 1000);
int dayNum = Integer.parseInt(String.valueOf(day));
if (dayNum > -1) {
for (int i = 0; i <= dayNum; i++) {
// 获取天数
System.out.println(getDateAdd("2017-08-23",i));
// 获取星期
System.out.println(dateToWeek(getDateAdd("2017-08-23",i)));
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
/**
* 获取开始日期到结束日期的天数
*
* @param date
* 传入字符串日期,例如:2011-01-03
* @param addNumber
* 传入整数
* @return
*/
public static String getDateAdd(String date, int addNumber) {
String returnStr = "";
StringTokenizer token = new StringTokenizer(date, "-");
int num = token.countTokens();
if (num == 3) {
int year;
int month;
int day;
year = Integer.parseInt(token.nextToken());
month = Integer.parseInt(token.nextToken());
day = Integer.parseInt(token.nextToken());
SimpleDateFormat formatter;
formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar calen = Calendar.getInstance();
calen.set(year, month - 1, day);
calen.add(5, addNumber); // 5代表日期,1代表年,2代表月
returnStr = formatter.format(calen.getTime());
} else
returnStr = date;
return returnStr;
}
/**
* 日期转星期
*
* @param datetime
* @return
*/
public static String dateToWeek(String datetime) {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
String[] weekDays = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
Calendar cal = Calendar.getInstance(); // 获得一个日历
Date datet = null;
try {
datet = f.parse(datetime);
cal.setTime(datet);
} catch (ParseException e) {
e.printStackTrace();
}
int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
if (w < 0)
w = 0;
return weekDays[w];
}