import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DateUtil
{
public static void main(String[] args) {
Calendar start = Calendar.getInstance();
start.set(2016 , 9 , 11);
Long startTIme = start.getTimeInMillis();
Calendar end = Calendar.getInstance();
end.set(2016, 10, 1);
Long endTime = end.getTimeInMillis();
Long oneDay = 1000 * 60 * 60 * 24l;
Long time = startTIme;
while (time <= endTime) {
Date d = new Date(time);
DateFormat df = new SimpleDateFormat("yyyyMMdd");
System.out.println(df.format(d));
time += oneDay;
}
System.out.println("-------------");
new DateUtil().printDate("2016-09-01" , "2016-09-01");
}
private static List<Date> dateSplit(Date startDate, Date endDate)
throws Exception {
if (!startDate.before(endDate)&&startDate.compareTo(endDate)==1){
throw new Exception("开始时间应该在结束时间之后");
}
Long spi = endDate.getTime() - startDate.getTime();
Long step = spi / (24 * 60 * 60 * 1000);// 相隔天数
List<Date> dateList = new ArrayList<Date>();
dateList.add(startDate);
for (int i = 1; i <= step; i++) {
dateList.add(new Date(dateList.get(i - 1).getTime()
+ (24 * 60 * 60 * 1000)));// 比上一天+一
}
return dateList;
}
public void printDate(String beginDate,String endDate){
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
Date start = sdf.parse(beginDate);
Date end = sdf.parse(endDate);
List<Date> lists = dateSplit(start, end);
if (!lists.isEmpty()) {
for (Date date : lists) {
System.out.println(sdf1.format(date));
}
}
} catch (Exception e) {
}
}
}
java开始与结束日期遍历
最新推荐文章于 2024-08-26 03:36:51 发布