首页 / JAVA / java 比较时间,DateDiff
java 比较时间,DateDiff
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java 比较时间,DateDiff,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2217字,纯文字阅读大概需要4分钟。
内容图文
![java 比较时间,DateDiff](/upload/InfoBanner/zyjiaocheng/632/13b674fd7eb24a1d8ec11d1c1755980f.jpg)
之前是自己用 Calendar 类写,比较繁琐,也容易出错。在别人(项目经理)的推荐下,了解了一个专门的工具类
DateDiff
实现方式也是通过 Calendar 的方式
import java.util.Calendar; import java.util.Date; public class DateDiff { /** * 按指定日期单位计算两个日期间的间隔 * * @param timeInterval, * @param date1, * @param date2 * @return date1-date2, */ public static synchronized long dateDiff(String timeInterval, Date date1, Date date2) {
if (timeInterval.equals("year")) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); int time = calendar.get(Calendar.YEAR); calendar.setTime(date2); return time - calendar.get(Calendar.YEAR); } if (timeInterval.equals("quarter")) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); int time = calendar.get(Calendar.YEAR) * 4; calendar.setTime(date2); time -= calendar.get(Calendar.YEAR) * 4; calendar.setTime(date1); time += calendar.get(Calendar.MONTH) / 4; calendar.setTime(date2); return time - calendar.get(Calendar.MONTH) / 4; } if (timeInterval.equals("month")) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); int time = calendar.get(Calendar.YEAR) * 12; calendar.setTime(date2); time -= calendar.get(Calendar.YEAR) * 12; calendar.setTime(date1); time += calendar.get(Calendar.MONTH); calendar.setTime(date2); return time - calendar.get(Calendar.MONTH); } if (timeInterval.equals("week")) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date1); int time = calendar.get(Calendar.YEAR) * 52; calendar.setTime(date2); time -= calendar.get(Calendar.YEAR) * 52; calendar.setTime(date1); time += calendar.get(Calendar.WEEK_OF_YEAR); calendar.setTime(date2); return time - calendar.get(Calendar.WEEK_OF_YEAR); } if (timeInterval.equals("day")) { long time = date1.getTime() / 1000 / 60 / 60 / 24; return time - date2.getTime() / 1000 / 60 / 60 / 24; } if (timeInterval.equals("hour")) { long time = date1.getTime() / 1000 / 60 / 60; return time - date2.getTime() / 1000 / 60 / 60; } if (timeInterval.equals("minute")) { long time = date1.getTime() / 1000 / 60; return time - date2.getTime() / 1000 / 60; } if (timeInterval.equals("second")) { long time = date1.getTime() / 1000; return time - date2.getTime() / 1000; } return date1.getTime() - date2.getTime(); } }
内容总结
以上是互联网集市为您收集整理的java 比较时间,DateDiff全部内容,希望文章能够帮你解决java 比较时间,DateDiff所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。