zoukankan      html  css  js  c++  java
  • (转)java获得两个时间的差

     /**
      * @param date1
      *            需要比较的时间 不能为空(null),需要正确的日期格式 ,如:2009-09-12
      * @param date2
      *            被比较的时间 为空(null)则为当前时间
      * @param stype
      *            返回值类型 0为多少天,1为多少个月,2为多少年
      * @return 举例: compareDate("2009-09-12", null, 0);//比较天
      *         compareDate("2009-09-12", null, 1);//比较月
      *         compareDate("2009-09-12", null, 2);//比较年
      */

     public int compareDate(String startDay, String endDay, int stype) {
      int n = 0;
      String[] u = { "天", "月", "年" };
      String formatStyle = stype == 1 ? "yyyy-MM" : "yyyy-MM-dd";

      endDay = endDay == null ? getCurrentDate("yyyy-MM-dd") : endDay;

      DateFormat df = new SimpleDateFormat(formatStyle);
      Calendar c1 = Calendar.getInstance();
      Calendar c2 = Calendar.getInstance();
      try {
       c1.setTime(df.parse(startDay));
       c2.setTime(df.parse(endDay));
      } catch (Exception e3) {
       System.out.println("wrong occured");
      }
      // List list = new ArrayList();
      while (!c1.after(c2)) { // 循环对比,直到相等,n 就是所要的结果
       // list.add(df.format(c1.getTime())); // 这里可以把间隔的日期存到数组中 打印出来
       n++;
       if (stype == 1) {
        c1.add(Calendar.MONTH, 1); // 比较月份,月份+1
       } else {
        c1.add(Calendar.DATE, 1); // 比较天数,日期+1
       }
      }
      n = n - 1;
      if (stype == 2) {
       n = (int) n / 365;
      }
      System.out.println(startDay + " -- " + endDay + " 相差多少" + u[stype]
        + ":" + n);
      return n;
     }

     public String getCurrentDate(String format) {
      Calendar day = Calendar.getInstance();
      day.add(Calendar.DATE, 0);
      SimpleDateFormat sdf = new SimpleDateFormat(format);// "yyyy-MM-dd"
      String date = sdf.format(day.getTime());
      return date;
     }

  • 相关阅读:
    JVM垃圾回收之三色标记
    负载均衡之LVS与Nginx对比
    浅析虚拟机内存管理模型
    JVM调优之垃圾定位、垃圾回收算法、垃圾处理器对比
    JAVA对象分析之偏向锁、轻量级锁、重量级锁升级过程
    全局负载均衡与CDN内容分发
    内存屏障在CPU、JVM、JDK中的实现
    JVM类加载与双亲委派机制被打破
    JVM虚拟机Class类文件研究分析
    Redis分布式锁升级版RedLock及SpringBoot实现
  • 原文地址:https://www.cnblogs.com/yongtaiyu/p/2567724.html
Copyright © 2011-2022 走看看