JAVA优化连续天数日期的展示
程序员文章站
2022-05-27 20:25:54
...
public class ContinuousTimeTest2 {
public static void main(String[] args) {
String timeString = "2021-03-01, 2021-01-02, 2021-01-01, 2020-12-27, 2020-12-31, 2020-12-28, 2021-02-28";
System.out.println("优化连续日期的显示: "+ continuousTime(timeString));
}
// 连续时间
public static String continuousTime(String timeString){
String[] dateStrings = timeString.split(",");
// 将日期字符串转换成日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 设置转换的宽松度,即区分闰年
sdf.setLenient(true);
Date[] dates = new Date[dateStrings.length];
List list = new ArrayList();
try {
// 循环将日期字符串转换成日期类
for(int i = 0; i < dateStrings.length; i++){
dates[i] = sdf.parse(dateStrings[i]);
}
// 排好序后的时间
Arrays.sort(dates);
System.out.print("排好序后的时间:");
for(int i = 0; i < dates.length; i++){
System.out.print(sdf.format(dates[i]) + ",");
list.add(dates[i]);
}
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println();
// System.out.println("formDate "+betterSyncTime(list));
// System.out.println("当前时间:" + sdf.format(new Date()));
return 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));
}
} 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)));
}
}
}
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;
}
}
}