java获取两个时间之间的日期,按天计算

2022-06-21 00:00:00 日期 获取 两个
public class Test { 

	public static void main(String[] args) throws Exception
	{ 
		List<String> lists = getBetweenTime("2019-01-02 21:20:12","2019-01-08 19:12:20");
		for(String list:lists)
		{ 
			System.out.println(list);
		}
// 2019-01-02
// 2019-01-03
// 2019-01-04
// 2019-01-05
// 2019-01-06
// 2019-01-07
// 2019-01-08
	}
	public static List<String> getBetweenTime(String starttime,String endtime)
    { 
    	List<String> betweenTime = new ArrayList<String>();
    	try
    	{ 
	    	Date sdate= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(starttime);
	    	Date edate= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(endtime);
	    	
	    	SimpleDateFormat outformat = new SimpleDateFormat("yyyy-MM-dd");
	        
	    	Calendar sCalendar = Calendar.getInstance();
	    	sCalendar.setTime(sdate);
	    	int year = sCalendar.get(Calendar.YEAR);
	        int month = sCalendar.get(Calendar.MONTH);
	        int day = sCalendar.get(Calendar.DATE);
	        sCalendar.set(year, month, day, 0, 0, 0);
	        
	        Calendar eCalendar = Calendar.getInstance();
	        eCalendar.setTime(edate);
	        year = eCalendar.get(Calendar.YEAR);
	        month = eCalendar.get(Calendar.MONTH);
	        day = eCalendar.get(Calendar.DATE);
	        eCalendar.set(year, month, day, 0, 0, 0);
	        
	        while (sCalendar.before(eCalendar))
	        { 
	        	betweenTime.add(outformat.format(sCalendar.getTime()));
	        	sCalendar.add(Calendar.DAY_OF_YEAR, 1);
	        }
	        betweenTime.add(outformat.format(eCalendar.getTime()));
    	}
    	catch(Exception e)
    	{ 
    		e.printStackTrace();
    	}
        return betweenTime;
    }
}
    原文作者:姚贤贤
    原文地址: https://blog.csdn.net/u011311291/article/details/89406107
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。

相关文章