import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class MonthUtils {
public static long getTimeStamp(DateTime dateTime){
return dateTime.getTime();
}
public static int getDaysOfMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* 获取两个日期之间的所有月份 (年月)
*
* @param startTime
* @param endTime
* @return:YYYY-MM
*/
public static List<String> getMonthBetweenDate(String startTime, String endTime){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
// 声明保存日期集合
List<String> list = new ArrayList<String>();
try {
// 转化成日期类型
Date startDate = sdf.parse(startTime);
Date endDate = sdf.parse(endTime);
//用Calendar 进行日期比较判断
Calendar calendar = Calendar.getInstance();
while (startDate.getTime()<=endDate.getTime()){
// 把日期添加到集合
list.add(sdf.format(startDate) + "-01");
// 设置日期
calendar.setTime(startDate);
//把日期增加一天
calendar.add(Calendar.MONTH, 1);
// 获取增加后的日期
startDate=calendar.getTime();
}
} catch (ParseException e) {
e.printStackTrace();
}
return list;
}
public static void main(String[] args) throws ParseException {
String startStr = "2021-02-26";
String endStr = "2022-03-09";
List<String> list = getMonthBetweenDate(startStr, endStr);
System.out.println(list);
}
}
01-13
2041
05-30
1602
11-22
6081
10-14
4087