日期操作(获取所有月份+分割时间段)
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);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!