日期:2014-05-20  浏览次数:20777 次

求两时间段具体的日期
怎么样求出任意的两时间段内的具体日期,比如开始时间是20060328结束时间是20060401
那么之间的日期是20060328、20060329、20060330、20060331、20060401

------解决方案--------------------
package org.luyang;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.omg.CORBA.DATA_CONVERSION;

import sun.util.calendar.CalendarDate;

/**
* DateUtil
*
* @author luyang
*
*/
public class DateUtil {

public static void main(String[] args) {
String str1 = "20060112 ";
String str2 = "20060203 ";
printDateBetweenTwo(str1, str2);
}

private static void printDateBetweenTwo(String date1, String date2) {
System.out.println(date1);
while (true) {
if (date1.compareTo(date2) < 0) {
date1 = getDayAfter(date1, 1);
System.out.println(date1);
} else {
break;
}
}
}

public static String getDayAfter(String dateFrom, int amount) {
Date dt = null;
Date date = null;
try {
dt = new SimpleDateFormat( "yyyyMMdd ").parse(dateFrom);
long times = dt.getTime();
long dateMillSec = 24l * 60 * 60 * 1000 * amount;
times = times + dateMillSec;
date = new Date(times);
} catch (ParseException e) {
return null;
}
return formatDate(date, "yyyyMMdd ");
}
}
------解决方案--------------------
DateFormat先格式化日期,生成Date,再转Calendar,然后就很方便计算了
------解决方案--------------------
import java.text.SimpleDateFormat;
import java.text.ParseException;
class TestDateFormat {
public static void printDate(String startDate, String endDate, String dateFroamt) {
try {
SimpleDateFormat format = new SimpleDateFormat(dateFroamt);
Calendar calStartDate = Calendar.getInstance();
calStartDate.setTime(format.parse(startDate));
Calendar calEndDate = Calendar.getInstance();
calEndDate.setTime(format.parse(endDate));
while (calStartDate.before(calEndDate)) {
calStartDate.add(Calendar.DAY_OF_YEAR, 1);
System.out.println(format.format(calStartDate.getTime()));

}
} catch (ParseException p) {
p.printStackTrace();
}
}
public static void main(String[] args) {
printDate( "20070102 ", "20070306 ", "yyyyMMdd ");
}
}