yongtaiyu

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 /**
  * @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;
 }

posted on 2012-06-28 15:47  yongtaiyu  阅读(584)  评论(0编辑  收藏  举报