关闭

java 中计算两个时间相差天数

293人阅读 评论(4) 收藏 举报
分类:

方式一:

private static long between_days;

public static int getDayNumByDate(Date oldTime, Date newTime) throws ParseException


    Calendar cal = Calendar.getInstance();     //获取日历实例
    cal.setTime(oldTime);    
    long time1 = cal.getTimeInMillis();                 
    cal.setTime(newTime);    

    long time2 = cal.getTimeInMillis();  

    if(time2>=time1){       

        between_days = (time2-time1)/(1000*3600*24);  

     }else{

          between_days = 0;

    }

    return Integer.parseInt(String.valueOf(between_days));   

}

方式二:

/**
 * 计算两个日期之间相差的天数
 *
 * @param smdate 较小的时间
 * @param bdate  较大的时间
 * @return 相差天数
 * @throws ParseException
 */
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));
}



1
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:62936次
    • 积分:1136
    • 等级:
    • 排名:千里之外
    • 原创:45篇
    • 转载:11篇
    • 译文:0篇
    • 评论:34条
    最新评论