java 获取两个时间之前所有的日期

正序(2017-01-01 ~2019-xxxxx)

 package com.founder.util;

 import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List; /**
* TODO
*
* @ClassName: Time
* @author: dh
* @since: 2019/9/25 15:32
*/
public class Time { /**
* 返回两个时间间隔内的所有日期
*
* @param dateStart eg:2017-1-1
* @param dateEnd eg:2019-9-25
* @return java.util.List<java.lang.String>
* @Title: getTwoDaysDay
*/ public static List<String> getTwoDaysDay(String dateStart, String dateEnd) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); List<String> dateList = new ArrayList<String>(); try {
Date dateOne = sdf.parse(dateStart);
Date dateTwo = sdf.parse(dateEnd); Calendar calendar = Calendar.getInstance();
calendar.setTime(dateOne); dateList.add(sdf.format(dateOne));
while (calendar.getTime().before(dateTwo)) {
calendar.add(Calendar.DAY_OF_MONTH, +1);
dateList.add(sdf.format(calendar.getTime()));
}
} catch (Exception e) {
e.printStackTrace();
}
return dateList;
}
}

倒序(2019-2-25 ~2017-01-01):

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List; /**
* TODO
*
* @ClassName: test
* @author: dh
* @since: 2019/9/25 10:21
*/
public class test { public static void main(String[] args) { Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String format = sdf.format(date); System.err.println(getTwoDaysDay("2017-1-1", format));
} public static List<String> getTwoDaysDay(String dateStart, String dateEnd) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); List<String> dateList = new ArrayList<String>(); try {
Date dateOne = sdf.parse(dateStart);
Date dateTwo = sdf.parse(dateEnd); Calendar calendar = Calendar.getInstance();
calendar.setTime(dateTwo); dateList.add(dateEnd);
while (calendar.getTime().after(dateOne)) {
calendar.add(Calendar.DAY_OF_MONTH, -1);
dateList.add(sdf.format(calendar.getTime()));
}
} catch (Exception e) {
e.printStackTrace();
}
return dateList;
}
}
上一篇:java判断两个时间相差得天数


下一篇:java 比较两个时间大小