日期的汇总

来源:互联网 发布:oracle数据库难学吗 编辑:程序博客网 时间:2024/06/06 02:19

很多功能我们都需要使用到日期,日期的转化、比较、关系,下面归纳汇总一下项目中常用的。


在原有月份上加减一个月


public Date addOneMonth(String month){SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月Date monthD=null;try {monthD = sdf.parse(month);} catch (ParseException e) {e.printStackTrace();}Calendar cl = Calendar.getInstance();          cl.setTime(monthD);          //正1加一个月,负1减一个月        cl.add(Calendar.MONTH, 1);          return cl.getTime();  }

获取两个月份之前的所有月份


//获取两个日期之间的所有月份--1:不要最后一个月;2:要最后一个月public static List<String> getAllDifferMonth(Date startDate, Date endDate,Integer isEnd){ArrayList<String> result = new ArrayList<String>();SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");//格式化为年月Calendar min = Calendar.getInstance();Calendar max = Calendar.getInstance();min.setTime(startDate);min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);max.setTime(endDate);max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), isEnd);Calendar curr = min;while (curr.before(max)) {    result.add(sdf.format(curr.getTime()));    curr.add(Calendar.MONTH, 1);}return result;}

比较两个月份的大小:转化为long类型


if(nextFirstDate.getTime()>pzdef.getCDate().getTime()){String date = sdf.format(pzdef.getCDate());set.add(date);}

日期常见格式:


SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");Date monthD = sdf.parse(month);String monthStr = sdf.format(month);

这些基本上是我们做到和日期项目的时候使用频次较高的方法。


原创粉丝点击