正序(2017-01-01 ~2019-xxxxx)
1 package com.founder.util; 2 3 import java.text.SimpleDateFormat; 4 import java.util.ArrayList; 5 import java.util.Calendar; 6 import java.util.Date; 7 import java.util.List; 8 9 /** 10 * TODO 11 * 12 * @ClassName: Time 13 * @author: dh 14 * @since: 2019/9/25 15:32 15 */ 16 public class Time { 17 18 /** 19 * 返回两个时间间隔内的所有日期 20 * 21 * @param dateStart eg:2017-1-1 22 * @param dateEnd eg:2019-9-25 23 * @return java.util.List<java.lang.String> 24 * @Title: getTwoDaysDay 25 */ 26 27 public static List<String> getTwoDaysDay(String dateStart, String dateEnd) { 28 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 29 30 List<String> dateList = new ArrayList<String>(); 31 32 try { 33 Date dateOne = sdf.parse(dateStart); 34 Date dateTwo = sdf.parse(dateEnd); 35 36 Calendar calendar = Calendar.getInstance(); 37 calendar.setTime(dateOne); 38 39 dateList.add(sdf.format(dateOne)); 40 while (calendar.getTime().before(dateTwo)) { 41 calendar.add(Calendar.DAY_OF_MONTH, +1); 42 dateList.add(sdf.format(calendar.getTime())); 43 } 44 } catch (Exception e) { 45 e.printStackTrace(); 46 } 47 return dateList; 48 } 49 }
倒序(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; } }