JAVA优化连续天数日期的展示
入参:
String d1 = “2018-7-22”;
String d2 = “2018-7-23”;
String d3 = “2018-7-24”;
String d4 = “2018-7-25”;
String d5 = “2018-7-27”;
需求:连续的日期需要展示成:
2018-07-22~2018-07-25
,2018-07-27.
text
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
public class Util {
private static int supplierID = 16551;
private static String Key = "209903b0-5f92-4759-9ea9-8723124f8c9e";
public static void main(String[] args) throws ParseException {
String d1 = "2018-7-22";
String d2 = "2018-7-23";
String d3 = "2018-7-24";
String d4 = "2018-7-25";
String d5 = "2018-7-27";
List list = new ArrayList();
list.add( new SimpleDateFormat("yyyy-MM-dd").parse(d1));
list.add( new SimpleDateFormat("yyyy-MM-dd").parse(d2));
list.add( new SimpleDateFormat("yyyy-MM-dd").parse(d3));
list.add( new SimpleDateFormat("yyyy-MM-dd").parse(d4));
list.add( new SimpleDateFormat("yyyy-MM-dd").parse(d5));
System.out.println("formDate "+betterSyncTime(list));
}
/**
* @Author Linliang
* @Description 优化连续日期的显示
* @Date 2018/7/19
* @Param
*/
static String betterSyncTime(List<Date> list) {
Date sDate = null;
Date eDate = null;
boolean isStart = true;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size() - 1; i++) {
if (differentDays(list.get(i), list.get(i+1)) == 1) {
if (isStart != false) {
sDate = list.get(i);
isStart = false;
}
if(i == (list.size()-2)){
eDate = list.get(i+1);
sb.append(sdf.format(sDate)).append("~").append(sdf.format(eDate)).append(".");
}
} else {
if (isStart != true ) {
eDate = list.get(i);
sb.append(sdf.format(sDate)).append("~").append(sdf.format(eDate)).append(",");
isStart = true;
} else {
sb.append(sdf.format(list.get(i))).append(",");
}
if(i == (list.size()-2)) {
sb.append(sdf.format(list.get(i+1))).append(".");
}
}
}
return sb.toString();
}
/**
* @Author Linliang
* @Description 计算两个日期相差几天
* @Date 2018/7/19
* @Param
*/
public static int differentDays(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
int day1 = cal1.get(Calendar.DAY_OF_YEAR);
int day2 = cal2.get(Calendar.DAY_OF_YEAR);
int year1 = cal1.get(Calendar.YEAR);
int year2 = cal2.get(Calendar.YEAR);
if (year1 != year2) //同一年
{
int timeDistance = 0;
for (int i = year1; i < year2; i++) {
if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) //闰年
{
timeDistance += 366;
} else //不是闰年
{
timeDistance += 365;
}
}
return timeDistance + (day2 - day1);
} else //不同年
{
return day2 - day1;
}
}
}

评论
登录后即可评论
分享你的想法,与作者互动
暂无评论