常用方法
一、时间类
1.获取当前月的第一天和最后一天
public List<String> getMonthDate(Date date) {
List<String> monthDate = new ArrayList<>();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String firstday, lastday;
// 获取前月的第一天
Calendar cale = Calendar.getInstance();
cale.setTime(date);
cale.add(Calendar.MONTH, 0);
cale.set(Calendar.DAY_OF_MONTH, 1);
firstday = format.format(cale.getTime());
// 获取前月的最后一天
cale = Calendar.getInstance();
cale.add(Calendar.MONTH, 1);
cale.set(Calendar.DAY_OF_MONTH, 0);
lastday = format.format(cale.getTime());
monthDate.add(firstday);
monthDate.add(lastday);
return monthDate;
}
2.获取当前月的天数并统计出每一天
public List<String> getDays(String startTime, String endTime) {
// 返回的日期集合
List<String> days = new ArrayList<String>();
//yyyy-MM-dd HH:mm:ss
//yyyy-MM-dd
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date start = dateFormat.parse(startTime);
Date end = dateFormat.parse(endTime);
Calendar tempStart = Calendar.getInstance();
tempStart.setTime(start);
Calendar tempEnd = Calendar.getInstance();
tempEnd.setTime(end);
tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
while (tempStart.before(tempEnd)) {
days.add(dateFormat.format(tempStart.getTime()));
tempStart.add(Calendar.DAY_OF_YEAR, 1);
}
} catch (ParseException e) {
e.printStackTrace();
}
return days;
}
3.获取两个日期相差的天数
public int getIntervalDays(Date startDate, Date endDate) {
return (int) Math.ceil(Math.abs(startDate.getTime() - endDate.getTime()) / 86400000);
}