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;
     }

  • 相关阅读:
    CGAffineTransform的使用大概:
    CYLTabBarController的简单使用
    Masonry详解
    Swift学习 (四)
    《Advanced Bash-scripting Guide》学习(二):测试脚本调用的参数是否正确
    《Advanced Bash-scripting Guide》学习(一):对一个增强和广义的删除logfile的脚本的理解
    [JSOI2007]字符加密Cipher
    codevs 3160 最长公共子串
    codevs 1500 后缀排序
    浅谈后缀数组
  • 原文地址:https://www.cnblogs.com/yongtaiyu/p/2567724.html
Copyright © 2011-2022 走看看