zoukankan      html  css  js  c++  java
  • java 比较时间,DateDiff

    之前是自己用 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(); } }
  • 相关阅读:
    【函数】wm_concat包的订制
    【云和恩墨】性能优化:Linux环境下合理配置大内存页(HugePage)
    【技巧】如何使用客户端发布BLOG+如何快速发布微信公众号文章
    【故障处理】队列等待之TX
    【转载】TX
    【转载】Linux磁盘管理:LVM逻辑卷管理
    【索引】Oracle之不可见索引和虚拟索引的比对
    小麦苗微信公众号文章链接地址
    Oracle 11g新特性direct path read引发的系统停运故障诊断处理
    常识之外:全表扫描为何产生大量 db file sequential read 单块读?
  • 原文地址:https://www.cnblogs.com/Kevin-QAQ/p/12917465.html
Copyright © 2011-2022 走看看