获得当前季度和已过季度的起始和结束时间
获得当前季度和已过季度的起始时间和结束时间
如:当前时间为:2018-09-08 15:12:00,那么当前季度为第三季度,这时要得到是
第一季度:"2018-01-01 00:00:00":"2018-03-31 23:59:59",
第二季度:"2018-04-01 00:00:00":"2018-06-30 23:59:59",
第三季度:"2018-07-01 00:00:00":"2018-08-25 09:27:46";
代码如下:
public static String[] getEveryQuarterStartAndEndTime(){ SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Calendar calendar = getInstance(); Map<String, Object> params = new HashMap<String, Object>(); String currentTime = formatter.format(calendar.getTime()); int year = calendar.get(Calendar.YEAR); int currentMonth = calendar.get(Calendar.MONTH); String startTime = ""; String endTime = ""; int season = (currentMonth)/3+1; String[] startAndEndSeason = new String[season]; for (int i = 0; i < season; i++) { params.clear(); switch (i) { case 0: //起始时间 calendar.set(year, 0, 1, 0, 0, 0); startTime = formatter.format(calendar.getTime()); //结束时间 calendar.set(year, 2, 31, 23, 59, 59); endTime = formatter.format(calendar.getTime()); params.put(startTime, endTime); startAndEndSeason[i] = JSON.toJSONString(params); break; case 1: //起始时间 calendar.set(year, 3, 1, 0, 0, 0); startTime = formatter.format(calendar.getTime()); //结束时间 calendar.set(year, 5, 30, 23, 59, 59); endTime = formatter.format(calendar.getTime()); params.put(startTime, endTime); startAndEndSeason[i] = JSON.toJSONString(params); break; case 2: //起始时间 calendar.set(year, 6, 1, 0, 0, 0); startTime = formatter.format(calendar.getTime()); params.put(startTime, currentTime); //结束时间 calendar.set(year, 8, 30, 23, 59, 59); endTime = formatter.format(calendar.getTime()); params.put(startTime, endTime); startAndEndSeason[i] = JSON.toJSONString(params); break; case 3: //起始时间 calendar.set(year, 9, 1, 0, 0, 0); startTime = formatter.format(calendar.getTime()); params.put(startTime, currentTime); //结束时间 calendar.set(year, 11, 31, 23, 59, 59); endTime = formatter.format(calendar.getTime()); params.put(startTime, endTime); startAndEndSeason[i] = JSON.toJSONString(params); break; default: break; } } return startAndEndSeason; }
调用执行方法:
public static void main(String[] args) { String[] strs = getEveryQuarterStartAndEndTime(); for (String str : strs) {
Map<String, Object> params = JSON.parseObject(str); System.err.println(str); } }
运行结果为: