java日期计算

1.  判断是否为当月最后一天

public boolean isLastDayofMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        Calendar last = Calendar.getInstance();
        calendar.setTime(date);
        last.set(Calendar.DAY_OF_MONTH, last.getActualMaximum(Calendar.DAY_OF_MONTH));
		
		// 1. 此方法时间精确到秒
        /*if (calendar.compareTo(last) == 0) { 
            return true;
        }*/
		
		// 2. 获取当月最大天数与当前日期比较
        String start = formatDate(date, "yyyy-MM-dd");
        String day = start.split("-")[2];
        int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); // 当月最大天数
        if (days == Integer.parseInt(day)) {
            return true;
        }
		
        return false;
    }

   /**
	* format date 
	**/
	public static String formatDate(Date date, String format) {
        try {
            if (StringUtil.isStrEmpty(format)) {
                format = "yyyy-MM-dd";
            }

            SimpleDateFormat dateFormat = new SimpleDateFormat(format);
            return dateFormat.format(date);
        } catch (Exception var3) {
            return "";
        }
    }

 2. 计算两个日期之间的天数


    public Integer calDateApart(String startDate, String endDate) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = new Date();
        Date d2 = new Date();
        try {
            d1 = df.parse(startDate);
            d2 = df.parse(endDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar start = Calendar.getInstance();
        start.setTime(d1); //设置当前时间
        Long startTime = start.getTimeInMillis();

        Calendar end = Calendar.getInstance();
        end.setTime(d2);
        Long endTime = end.getTimeInMillis();

        Long oneDay = 1000 * 60 * 60 * 24l;

        Long days = (endTime - startTime) / oneDay;
        int day = NumberTool.safeToInteger(days, 0);
        return day;
    }

 

你可能感兴趣的:(java日期计算)