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(); } }
  • 相关阅读:
    Google Web 字体 API 访谈
    关于如何跨越抄袭程序阶段的一些断想
    DirectX开发中找不到dxtrans.h的问题的解决
    Google Web 字体 API 访谈
    NetBeans 6.9 发布后选版 1 已经可用
    Thrift java服务器与客户端示例
    Wing IDE Pro v. 4.1.91 Python Wingware Python IDE
    tkang's blog
    Thrift的简单使用
    maven加载自己的包
  • 原文地址:https://www.cnblogs.com/Kevin-QAQ/p/12917465.html
Copyright © 2011-2022 走看看