码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-01-02 17:33:53      阅读:374      评论:0      收藏:0      [点我收藏+]

标签:com   lis   replace   out   oid   .com   gety   ati   oca   

 

     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个日期里面的所有月份

标签:com   lis   replace   out   oid   .com   gety   ati   oca   

原文地址:https://www.cnblogs.com/liw66/p/10209294.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!