/**
* 两个日期之间的年List,或者月List,或者日期List
*
* @param date1 开始日期
* @param date2 结束日期
* @param type 类型:年、月、日
* @return
*/
public static List<String> getDateList(String date1, String date2, String type) {
List list = new ArrayList();
String format = "yyyy-MM-dd";
int cType = 0;
if ("day".equals(type)) {
format = "yyyy-MM-dd";
cType = Calendar.DATE;
} else if ("month".equals(type)) {
format = "yyyy-MM";
cType = Calendar.MONTH;
} else if ("year".equals(type)) {
format = "yyyy";
cType = Calendar.YEAR;
}
SimpleDateFormat sf = new SimpleDateFormat(format);
try {
Date startDate = sf.parse(date1);
Date endDate = sf.parse(date2);
Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();
c1.setTime(startDate);
c2.setTime(endDate);
list.add(sf.format(c1.getTime()));
while (c1.compareTo(c2) < 0) {
c1.add(cType, 1);// 开始日期加一个月直到等于结束日期为止
Date ss = c1.getTime();
String str = sf.format(ss);
list.add(str);
}
System.out.print(list);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
public static String formatDate(String date){
String format = "yyyy-MM-dd";
SimpleDateFormat sf = new SimpleDateFormat(format);
String str = null;
try {
str = sf.format(sf.parse(date));
} catch (ParseException e) {
e.printStackTrace();
}
return str;
}
//比较两个日期大小
public static int compare_date(String DATE1, String DATE2, String format) {
DateFormat df = new SimpleDateFormat(format);
try {
Date dt1 = df.parse(DATE1);
Date dt2 = df.parse(DATE2);
if (dt1.getTime() > dt2.getTime()) {
// System.out.println("dt1 在dt2前");
return 1;
} else if (dt1.getTime() < dt2.getTime()) {
// System.out.println("dt1在dt2后");
return -1;
} else {
return 0;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return 0;
}
---------------------
【转载,仅作分享,侵删】
作者:xinyuebaihe
原文:https://blog.csdn.net/xinyuebaihe/article/details/88099167
版权声明:本文为博主原创文章,转载请附上博文链接!
|
|