获取两个日期之间的月份 (具体月份)一个是包含头尾 一个不包含头尾
作者:互联网
最近再做一个项目 要计算连个月之间的相差的月份 网上特别多的是计算相差月份数 相差几个月 这个就不贴出来了 一百度全是的 完了之后就是相差月份详细的每个月不包括头尾的 比如计算 2018-12-12-2019-03-31相差的月份是 2019-01 02 "并没有算出 201812 和2019 03月份代码如下:
Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.set(2014, 9, 30); c2.setTime(new Date()); System.out.println(c1.get(Calendar.YEAR) + " " + c1.get(Calendar.MONTH)); while (c1.before(c2)) { int m = c1.get(Calendar.MONTH) + 1; System.out.println(c1.get(Calendar.YEAR) + " " + (c1.get(Calendar.MONTH) + 1)); c1.add(Calendar.MONTH, 1); } System.out.println(c1.get(Calendar.YEAR) + " " + (c1.get(Calendar.MONTH) + 1));
这个似乎第一个输出和第二输出 是包含头尾的 但是如果输入相同的日期 ,理想的情况只需要输出一个月份就行 但是实际会输出俩个
所有有了以下的代码:
Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); c1.set(2016, 12, 1); c2.set(2019, 12, 30); String time = ""; String time2 = ""; Integer i = c1.get(Calendar.MONTH); StringBuffer month = new StringBuffer("0"); StringBuffer mon = new StringBuffer("0"); if (i == 0) { i = 12; time = String.valueOf(c1.get(Calendar.YEAR) - 1) + "" + i; } else if (String.valueOf(i).length() < 2) { month.append(i + ""); time = String.valueOf(c1.get(Calendar.YEAR)) + month + ""; } else { time = String.valueOf(c1.get(Calendar.YEAR)) + "" + String.valueOf(c1.get(Calendar.MONTH)); } if (String.valueOf(c2.get(Calendar.MONTH)).length() < 2) { mon.append(c2.get(Calendar.MONTH)); time2 = String.valueOf(c2.get(Calendar.YEAR)) + mon + ""; } else { time2 = String.valueOf(c2.get(Calendar.YEAR)) + "" + String.valueOf(c2.get(Calendar.MONTH)); } while (Integer.valueOf(time2) >= Integer.valueOf(time)) { System.out.println(time); month = new StringBuffer("0"); mon = new StringBuffer("0"); i = c1.get(Calendar.MONTH) + 1; if (String.valueOf(i).length() < 2) { month.append(i + ""); time = String.valueOf(c1.get(Calendar.YEAR)) + month + ""; } else { time = String.valueOf(c1.get(Calendar.YEAR)) + "" + String.valueOf(c1.get(Calendar.MONTH) + 1); } if (String.valueOf(c2.get(Calendar.MONTH)).length() < 2) { mon.append(c2.get(Calendar.MONTH)); time2 = String.valueOf(c2.get(Calendar.YEAR)) + mon + ""; } else { time2 = String.valueOf(c2.get(Calendar.YEAR)) + "" + String.valueOf(c2.get(Calendar.MONTH)); } c1.add(Calendar.MONTH, 1); } }
看上去很多 很蠢但是这个解决了我想要的数据 如果有更好的方法,请多多指教
标签:头尾,valueOf,String,包含,get,月份,MONTH,Calendar,c1 来源: https://www.cnblogs.com/blackCatFish/p/11785876.html