java计算两时间间隔几天,几小时,几分钟

思路是:
先计算两日期的毫秒数,然后根据每天的毫秒数,每小时的毫秒数,每分钟的毫秒数去计算相差几天,几分钟,几小时

业务需求:

计算数据库中查询出的时间距现在多长时间。

代码实现:
private String timeCalculate(String time) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String nowTimeStr = sdf.format(System.currentTimeMillis());
    //每天毫秒数
    long nd = 1000 * 24 * 60 * 60;
    //每小时毫秒数
    long nh = 1000 * 60 * 60;
    //每分钟毫秒数
    long nm = 1000 * 60;

    Date nowDate = sdf.parse(nowTimeStr);
    Date date = sdf.parse(time);

    long diff = nowDate.getTime() - date.getTime();

    // 计算差多少天
    long day = diff / nd;
    // 计算差多少小时
    long hour = diff % nd / nh;
    // 计算差多少分钟
    long min = diff % nd % nh / nm;
    
    if (day == 0 && hour == 0 && min <1){
        return "刚刚";
    }else if(day ==0 && hour < 1){
        return min+"分钟前";
    }else if (day <1 && hour >=1){
        return hour+"小时前";
    }else {
        return day+"天前";
    }
}

测试调用:

public static void main(String[] args) throws ParseException {
    System.out.println(DateTimeTest.timeCalculate("2019-09-06 09:55:00"));;
}

结果:

1分钟前

相差天数计算:
public static final int daysBetween(Date early, Date late) { 
     
         java.util.Calendar calst = java.util.Calendar.getInstance();   
         java.util.Calendar caled = java.util.Calendar.getInstance();   
         calst.setTime(early);   
          caled.setTime(late);   
          //设置时间为0时   
          calst.set(java.util.Calendar.HOUR_OF_DAY, 0);   
          calst.set(java.util.Calendar.MINUTE, 0);   
          calst.set(java.util.Calendar.SECOND, 0);   
          caled.set(java.util.Calendar.HOUR_OF_DAY, 0);   
          caled.set(java.util.Calendar.MINUTE, 0);   
          caled.set(java.util.Calendar.SECOND, 0);   
         //得到两个日期相差的天数   
          int days = ((int) (caled.getTime().getTime() / 1000) - (int) (calst   
                 .getTime().getTime() / 1000)) / 3600 / 24;   
          
         return days;   
    }   
   
    
    public static void main(String[] args)
    {
         Date earlydate = new Date();   
         Date latedate = new Date();   
         DateFormat df = DateFormat.getDateInstance();   
         try {   
             earlydate = df.parse("2009-09-21");   
             latedate = df.parse("2009-10-16");   
         } catch (ParseException e) {   
               e.printStackTrace();   
           }   
          int days = daysBetween(earlydate,latedate);   
          System.out.println(days);   
    }

你可能感兴趣的:(Java开发进阶)