java 日期操作方法

  /**  
     * 计算两个日期之间相差的天数  
     * @param smdate 较小的时间 
     * @param bdate  较大的时间 
     * @return 相差天数 
     * @throws ParseException  
     */
    public static int daysBetween(Date smdate, Date bdate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            smdate = sdf.parse(sdf.format(smdate));
            bdate = sdf.parse(sdf.format(bdate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        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 + 1));
    }

    /**
     * 得到两个日期中的每一天
     * @param startTime
     * @param endTime
     * @return
     */
    public static List<Date> getEveryDaysList(Date startTime, Date endTime) {
        Date startDay = DateUtils.truncate(startTime, Calendar.DAY_OF_MONTH);
        Date endDay = DateUtils.truncate(endTime, Calendar.DAY_OF_MONTH);
        List<Date> resultList = new ArrayList<Date>();
        for (Date day = startDay; day.before(endDay); day = DateUtils.add(day, Calendar.DAY_OF_MONTH, 1)) {
            resultList.add(day);
        }
        resultList.add(endDay);
        return resultList;
    }

    /**
     * 判断 date是否在 startDate和endDate之间
     * @param date
     * @param startDate
     * @param endDate
     * @return
     */
    public static boolean isBetweenDays(Date date, Date startDate, Date endDate) {
        boolean result = true;
        if (date.before(startDate) || date.after(endDate)) {
            result = false;
        }
        return result;
    }

    public static void main(String[] args) throws ParseException {
        // TODO Auto-generated method stub  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d1 = sdf.parse("2013-09-26");
        Date d2 = sdf.parse("2013-09-25");
        Date d3 = sdf.parse("2013-09-27");
        System.out.println(isBetweenDays(d1, d2, d3));
        System.out.println(daysBetween(d1, d3));
        List<Date> days = getEveryDaysList(d1, d3);
        for (Date day : days) {
            System.out.println(day);
        }
    }

你可能感兴趣的:(java)