java 获取两个时间差 年月日 时分秒 格式

public static String dateToString(Date d) {
    if (d == null) {
        return "";
    }
    //天数
    long nd = 1000 * 24 * 60 * 60;
    //小时
    long nh = 1000 * 60 * 60;
    //分钟
    long nm = 1000 * 60;
    //秒
    long ns = 1000;

    String date = "";
    Calendar cal1 = Calendar.getInstance();
    cal1.setTime(d);
    //当前时间
    Calendar cal2 = Calendar.getInstance();
    cal2.setTime(new Date());

    //只要年月
    int fromYear = cal1.get(Calendar.YEAR);
    int fromMonth = cal1.get(Calendar.MONTH);

    int toYear = cal2.get(Calendar.YEAR);
    int toMonth = cal2.get(Calendar.MONTH);

    //计算时间差
    long diff = cal2.getTime().getTime() - cal1.getTime().getTime();

    // 计算差多少天
    long day = diff / nd;
    // 计算差多少小时
    long hour = diff % nd / nh;
    // 计算差多少分钟
    long min = diff % nd % nh / nm;
    // 计算差多少秒
    long ss = diff % nd % nh % nm / ns;
    //计算月数
    int month = toMonth - fromMonth;
    //计算年数
    int year = toYear - fromYear;
    if (ss < 60 && ss > 0) {
        date = ss + "秒前";
    }
    if (min < 60 && min > 0) {
        date = min + "分钟前";
    }
    if (hour < 60 && hour > 0) {
        date = hour + "小时前";
    }
    if (day > 0) {
        date = day + "天前";
    }
    if (month > 0) {
        date = month + "月前";
    }
    if (year > 0) {
        date = year + "年前";
    }
    return date;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值