import java.text.SimpleDateFormat; import java.util.Calendar; /** * @Description 时间转换工具类 * @PackageName com.leo.tms.utils * @Author Simon Liu * @Date 2019年06月03日 10:44:28 */ public class DateUtil { /* * @Description: 获取指定某年某月份的最后一天 * @Date 2019/6/3 10:52 * @param: yearMonth yyyy-MM格式 * @return: java.lang.String */ public static String getLastDayOfMonth(String yearMonth) { int year = Integer.parseInt(yearMonth.split("-")[0]); //年 int month = Integer.parseInt(yearMonth.split("-")[1]); //月 Calendar cal = Calendar.getInstance(); // 设置年份 cal.set(Calendar.YEAR, year); // 设置月份 cal.set(Calendar.MONTH, month - 1); // 获取某月最大天数 int lastDay = cal.getActualMaximum(Calendar.DATE); // 设置日历中月份的最大天数 cal.set(Calendar.DAY_OF_MONTH, lastDay); // 格式化日期 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); return sdf.format(cal.getTime()); } /* * @Description: 如日期格式为 yyyyMM 则需要拼接个"-" */ public static void main(String[] args) { StringBuilder sb = new StringBuilder("201902"); //sb.insert(6, "-00"); sb.insert(4, "-"); System.out.println(sb); //输出 2019-02 System.out.println(getLastDayOfMonth(sb.toString())); //输出 20190228 }
/** * @param smdate * @param bdate * @return int * @Description: 两个日期相差天数 */ public static int daysBetween(Date smdate, Date bdate) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); smdate = sdf.parse(sdf.format(smdate)); bdate = sdf.parse(sdf.format(bdate)); Calendar cal = Calendar.getInstance(); cal.setTime(smdate); long time1 = cal.getTimeInMillis(); cal.setTime(bdate); long time2 = cal.getTimeInMillis(); long between_days = (time2 - time1) / (1000 * 3600 * 24); return Integer.parseInt(String.valueOf(between_days)); } /** * @param smdate * @param bdate * @throws ParseException * @return int * @Description: 两个月份相差月数 */ public static int monthsBetween(Date smdate, Date bdate) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); smdate = sdf.parse(sdf.format(smdate)); bdate = sdf.parse(sdf.format(bdate)); Calendar cal1 = Calendar.getInstance(); Calendar cal2 = Calendar.getInstance(); cal1.setTime(smdate); cal2.setTime(bdate); int year = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR); return year * 12 + cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH); }
}