获取到两个时间中间相差的月份
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72package com.ext.web.report; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; public class Test { /** * 获取到两个时间相差的月份,不包含enddate所在的月份 * @param begindate * @param enddate * @throws ParseException */ private static List<Integer> getMonth(String begindate, String enddate) throws ParseException { SimpleDateFormat date = new SimpleDateFormat("yyyy-MM-dd"); Date d1 = date.parse(begindate); Date d2 = date.parse(enddate); Calendar c1 = Calendar.getInstance(); Calendar c2 = Calendar.getInstance(); c1.setTime(d1); c2.setTime(d2); int a =(c2.get(Calendar.YEAR)-c1.get(Calendar.YEAR))*12+c2.get(Calendar.MONTH)-c1.get(Calendar.MONTH); String[] str = begindate.split("-"); String month = str[1]; int monthnum = Integer.valueOf(month); List<Integer> lists = new ArrayList<Integer>(); lists.add(monthnum); int t = 1; for(int i=1;i <a;i++){ int num = monthnum + i; if(num < 13){ lists.add(num); }else{ int mnum = num-12*t; lists.add(mnum); if(mnum == 12){ t = t+1; } } } return lists; } /** * 获取到两个时间相差的年份,例如 2000-2020,返回回来的是一个2000(包含)-2020(包含)的所有年份 * @param begindate * @param enddate * @throws ParseException */ private static List<String> getYear(String begindate, String enddate) throws ParseException { List<String> lists = new ArrayList<String>(); String benginYear = begindate; String endYear =enddate; int a = Integer.valueOf(endYear) - Integer.valueOf(benginYear); for(int i = 0;i<=a;i++){ String date = String.valueOf(Integer.valueOf(benginYear)+i) ; lists.add(date); } return lists; } public static void main(String[] args) throws ParseException { String begindate = "2020-01-01"; String enddate = "2030-01-01"; //System.out.println(Test.getMonth(begindate, enddate)); /*List<String> list =Test.getYear(begindate, enddate); for(int i =0 ;i<list.size();i++){ System.out.println(list.get(i)); }*/ } }
最后
以上就是无限发箍最近收集整理的关于JAVA中获取到两个时间之间的中间月份的全部内容,更多相关JAVA中获取到两个时间之间内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复