日期操作(获取所有月份+分割时间段)
作者:互联网
日期操作(获取所有月份+分割时间段)
/*
* 获取所有的的月份
*/
private static List<String> getInitMonthMapWithZero() {
List<String> list = new ArrayList<String>();
Calendar c = Calendar.getInstance();
for (int i = 0; i < 12; i++) {
int k = c.get(Calendar.YEAR);
int j = c.get(Calendar.MONTH) + 1 - i;
String date = "";
if (j >= 1) {
date = k + "-" + (j >= 10 ? "" : "0") + j;
} else {
int p = 11 - i;// 剩余循环次数
int m = c.get(Calendar.YEAR) - 1;
int n = c.get(Calendar.MONTH) + 2 + p;
date = m + "-" + (n >= 10 ? "" : "0") + n;
}
list.add(date);
}
return list;
}
* 按照指定小时分割时间段
*
* @param dateType 类型 M/D/H/N -->每月/每天/每小时/每分钟
* @param dBegin开始时间
* @param dEnd结束时间
* @param time 指定小时(如:1、2、3、4)
* @return
*/
public static List<String> findDates(String dateType, Date dBegin, Date dEnd, int time) throws Exception {
List<String> listDate = new ArrayList<>();
listDate.add(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(dBegin));
Calendar calBegin = Calendar.getInstance();
calBegin.setTime(dBegin);
Calendar calEnd = Calendar.getInstance();
calEnd.setTime(dEnd);
while (calEnd.after(calBegin)) {
if ("H".equals(dateType)) {
calBegin.add(Calendar.HOUR, time);
}
if ("M".equals(dateType)) {
calBegin.add(Calendar.MONTH, time);
}
if ("D".equals(dateType)) {
calBegin.add(Calendar.DATE, time);
}
if ("N".equals(dateType)) {
calBegin.add(Calendar.MINUTE, time);
}
if (calEnd.after(calBegin)) {
listDate.add(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(calBegin.getTime()));
} else {
listDate.add(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(calEnd.getTime()));
}
}
return listDate;
}
public static void main(String[] args) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat nowDate = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String format = nowDate.format(date);
String startDate = format.concat(" 00:00");
String endDate = format.concat(" 23:59");
Date dBegin = sdf.parse(startDate);
Date dEnd = sdf.parse(endDate);
List<String> list = findDates("H", dBegin, dEnd, 3);
for (String str : list) {
System.out.println(str);
}
}
标签:分割,String,format,add,日期,calBegin,时间段,new,Calendar 来源: https://www.cnblogs.com/hhs-5120/p/16656843.html