现在的位置: 首页 > 综合 > 正文

计算目标日期和当天相差天数

2018年02月10日 ⁄ 综合 ⁄ 共 691字 ⁄ 字号 评论关闭

    /**
     * 计算目标日期和当天相差天数
     * @param date 目标日期 格式yyyy-MM-dd
     * @return int 和当天相差天数
     */
private int getDays(String date) {
Calendar today = Calendar.getInstance();
Calendar target = Calendar.getInstance();

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
Date todayDate = new Date();
today.setTime(df.parse(df.format(todayDate)));
today.set(Calendar.HOUR, 0);
today.set(Calendar.MINUTE, 0);
today.set(Calendar.SECOND, 0);
target.setTime(df.parse(date));
target.set(Calendar.HOUR, 0);
target.set(Calendar.MINUTE, 0);
target.set(Calendar.SECOND, 0);
} catch (ParseException e) {
e.printStackTrace();
return 0;
}
long intervalMilli = target.getTimeInMillis() - today.getTimeInMillis();
int days = (int) (intervalMilli / (24 * 60 * 60 * 1000));

return days;
}

抱歉!评论已关闭.