Java获取2个日期里面的所有月份

Posted liw66

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java获取2个日期里面的所有月份相关的知识,希望对你有一定的参考价值。

 

     public static void main(String[] args) {
		
		String t1="2018-08-01";
		t1 = t1.replaceAll("(\d{4})\-(\d{2})\-\d{2}", "$1-$2-01");
		//String t2="2024-11-30";	
		//String t2="2018-01-30";
		//String t2="2019-09-30";
		String t2 = "2019-09-31";
		t2 = t2.replaceAll("(\d{4})\-(\d{2})\-\d{2}", "$1-$2-01");

		List<String> monthArea = getMonthArea(t1,t2);
		
		for(String t : monthArea) {
			System.out.println(t);
		}
		
	}
	private static List<String> getMonthArea(String t1,String t2) {
		
		LocalDate startDate = LocalDate.parse(t1);
		LocalDate endDate = LocalDate.parse(t2);
		
		List<String> monthArea = new ArrayList<>();
		
		if (startDate.compareTo(endDate)>0) {
			return monthArea;		
		}
		
		int startYear = startDate.getYear();
		int startMonth = startDate.getMonthValue();
		
		int endYear = endDate.getYear();
		int endMonth = endDate.getMonthValue();
				
		if (startYear==endYear) {
			for(int i=startMonth;i<=endMonth;i++) {				
				monthArea.add(startYear+"-"+getMyMonth(i));
			}				
		}else {		
			for(int i=startYear;i<=endYear;i++) {
				if (i == startYear ) {
					calcStartYear(monthArea,startYear,startMonth);				
				}else if (i == endYear){
					calcEndYear(monthArea,endYear,endMonth);
				}else {
					calcOneYear(monthArea,i);
				}
			}			
		}
		
		return monthArea;
		
	}
	private static void calcStartYear(List<String> monthArea,int startYear,int startMonth) {
		for(int i=startMonth;i<=12;i++) {				
			monthArea.add(startYear+"-"+getMyMonth(i));			
		}
	}
	private static void calcOneYear(List<String> monthArea,int year) {
		for(int i=1;i<=12;i++) {
			monthArea.add(year+"-"+getMyMonth(i)); 
		}		
	}
	private static void calcEndYear(List<String> monthArea,int endYear,int endMonth) {
		for(int i=1;i<=endMonth;i++) {		
			monthArea.add(endYear+"-"+getMyMonth(i));		
		}
	}	
	private static String getMyMonth(int month){
		String result = "";
		if (month<10) {
			result = "0" + Integer.toString(month);
		}else {
			result = Integer.toString(month);
		}
		return result;
	}

  

以上是关于Java获取2个日期里面的所有月份的主要内容,如果未能解决你的问题,请参考以下文章

Excel中,如何用函数获取当前日期(即系统日期)的月份值?谢谢

Java获取两个日期之间的所有月份

获取2个日期之间的月份

获取两个日期之间的所有月份

PHP日期操作类代码-农历-阳历转换闰年计算天数等

获取当前日期和时间