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; }
java 获取两个时间差 年月日 时分秒 格式
最新推荐文章于 2023-11-13 14:32:14 发布