最代码官方
2016-09-02 19:06:16
证
java计算两个日期之间的天数,并格式化返回天小时分钟的代码片段
import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtil { public static void main(String[] args) throws ParseException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date1 = format.parse("2012-10-11 07:18:54"); Date date2 = format.parse("2012-12-11 09:18:44"); String diff = diffDate(date1.getTime(), date2.getTime()); System.out.println(diff); } /** * 获取两个时间的时间查 如1天2小时30分钟 */ public static String diffDate(long from, long to) { String diff = ""; long nd = 1000 * 24 * 60 * 60; long nh = 1000 * 60 * 60; long nm = 1000 * 60; // long ns = 1000; // 获得两个时间的毫秒时间差异 long _diff = to - from; if (_diff <= 0) { diff = "0d"; return diff; } // 计算差多少天 long day = _diff / nd; // 计算差多少小时 long hour = _diff % nd / nh; // 计算差多少分钟 long min = _diff % nd % nh / nm; // 计算差多少秒//输出结果 // long sec = diff % nd % nh % nm / ns; if (day > 0) { diff += day + "d "; } if (hour > 0) { diff += hour + "h "; } if (min > 0) { diff += min + "m"; } return diff; } }
运行截图
当然可以按自己的业务需求实现按年月日小时分钟秒的计算。
猜你喜欢
请下载代码后再发表评论
![最代码相关代码源代码列表](https://static.zuidaima.com/resource/img/heart_ico.png)
![最代码最近下载分享源代码列表](https://static.zuidaima.com/resource/img/heart_ico.png)
![最代码最近浏览分享源代码列表](https://static.zuidaima.com/resource/img/cattle_ico.png)
梅梅呀 LV3
2022年7月5日
特雷西哈哈
2021年12月13日
暂无贡献等级
Mywang LV4
2021年11月19日
2196316269 LV10
2021年2月24日
刘孟彪 LV9
2020年12月30日
如夝萌灵 LV1
2020年5月26日
zengxueqi
2020年4月16日
暂无贡献等级
943609920 LV10
2020年1月8日
FFF112233 LV8
2019年11月6日
chenlong123
2019年10月31日
暂无贡献等级