前言:发现开发过程当中要用到时间和日历的情况太多了,这里把我碰到的情况记录一下。
1,获取某月天数
2,获取两个日期之间的天数
3,查询当前日期前(后)x天的日期
4,获取某日期的前(后)N月的年月
5,周六周日判断
正文:
1,获取某月天数
public static int getMaxDay(int year, int month) { Calendar cal = Calendar.getInstance(); //创建对象。不用new Calendar()的原因是Calendar是一个抽象类,且其构造方法是protected cal.clear(); //将所有字段值和时间值设置为未定义。Calendar类在set的时候,并不会立即生效,只有在get的时候才会生效,所以要先清理 cal.set(Calendar.YEAR, year); cal.set(Calendar.MONTH, month-1); return time.getActualMaximum(Calendar.DAY_OF_MONTH); }
2,获取两个日期之间的天数
扫描二维码关注公众号,回复:
6254525 查看本文章
//meiosisDate 减数 //minuendDate 被减数 public static int daysBetween(Date meiosisDate,Date minuendDate) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = Calendar.getInstance(); meiosisDate = sdf.parse(sdf.format(meiosisDate)); cal.setTime(meiosisDate); long time1 = cal.getTimeInMillis(); minuendDate = sdf.parse(sdf.format(minuendDate)); cal.setTime(minuendDate); long time2 = cal.getTimeInMillis(); long between_days=(time1-time2)/(1000*3600*24); return Integer.parseInt(String.valueOf(between_days)); }
3,查询当前日期前(后)x天的日期
//查询当前日期前(后)x天的日期(如果day数为负数,说明是此日期前的天数) public static String beforeNumberDay(int day) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date now = new Date(); Calendar c = Calendar.getInstance(); c.setTime(now); c.add(Calendar.DAY_OF_YEAR, day); String theDate = sdf.format(c.getTime()); return theDate; }
4,获取某日期的前(后)N月的年月
//获取某日期的前(后)N月的年月 public static String yearMonthPrevNumber(String theDate, int num) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); Date date = sdf.parse(theDate); Calendar c = Calendar.getInstance(); c.setTime(date); c.add(Calendar.MONTH, num); Date resultDate = c.getTime(); String yearMonthPrevNumber = sdf.format(resultDate); return yearMonthPrevNumber; }
5,周六周日判断
public static boolean isWeekend(Date date) { boolean isWeekend = false; Calendar cal = Calendar.getInstance(); cal.setTime(date); if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) { isWeekend = true; } return isWeekend; }