JAVA优化连续天数日期的展示\n\n入参: \nString d1 = “2018-7-22”; \n String d2 = “2018-7-23”; \n String d3 = “2018-7-24”; \n String d4 = “2018-7-25”; \n String d5 = “2018-7-27”; \n需求:连续的日期需要展示成:...
入参: 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-27.
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;
}
}
}
本站为非盈利网站,如果您喜欢这篇文章,欢迎支持我们继续运营!
本站主要用于日常笔记的记录和生活日志。本站不保证所有内容信息可靠!(大多数文章属于搬运!)如有版权问题,请联系我立即删除:“abcdsjx@126.com”。
QQ: 1164453243
邮箱: abcdsjx@126.com