1.util
package com.etone.job.report.util; 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 GetMontnUtil { /** * * @param minDate 最小时间 2015-01 * @param maxDate 最大时间 2015-10 * @return 日期集合 格式为 年-月 * @throws Exception */ public static List<String> getMonthBetween(String minDate, String maxDate) throws Exception { ArrayList<String> result = new ArrayList<String>(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月 Calendar min = Calendar.getInstance(); Calendar max = Calendar.getInstance(); min.setTime(sdf.parse(minDate)); min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1); max.setTime(sdf.parse(maxDate)); max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2); Calendar curr = min; while (curr.before(max)) { result.add(sdf.format(curr.getTime())); curr.add(Calendar.MONTH, 1); } return result; } /** * 获取指定日期所在月份开始的时间戳 * @param date 指定日期 * @return */ public static Long getMonthBegin(String date) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date time = format.parse(date); Calendar c = Calendar.getInstance(); c.setTime(time); //设置为1号,当前日期既为本月第一天 c.set(Calendar.DAY_OF_MONTH, 1); //将小时至0 c.set(Calendar.HOUR_OF_DAY, 0); //将分钟至0 c.set(Calendar.MINUTE, 0); //将秒至0 c.set(Calendar.SECOND,0); //将毫秒至0 c.set(Calendar.MILLISECOND, 0); // 获取本月第一天的时间戳 return c.getTimeInMillis(); } /** * 获取指定日期所在月份结束的时间戳 * @param date 指定日期 * @return */ public static Long getMonthEnd(String date) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date time = format.parse(date); Calendar c = Calendar.getInstance(); c.setTime(time); //设置为当月最后一天 c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH)); //将小时至23 c.set(Calendar.HOUR_OF_DAY, 23); //将分钟至59 c.set(Calendar.MINUTE, 59); //将秒至59 c.set(Calendar.SECOND,59); //将毫秒至999 c.set(Calendar.MILLISECOND, 999); // 获取本月最后一天的时间戳 return c.getTimeInMillis(); } }实例
try { Long monthBegin = GetMontnUtil.getMonthBegin("2019-05-22"); Long monthEnd = GetMontnUtil.getMonthEnd("2019-05-22"); System.out.println("monthBegin:" + monthBegin); System.out.println("monthEnd:" + monthEnd); } catch (ParseException e) { e.printStackTrace(); }结果,十三位要自己处理为十位的时间戳
monthBegin:1556640000000 monthEnd:1559318399999