日期的汇总

xiaoxiao2021-02-28  66

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

在原有月份上加减一个月

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); 这些基本上是我们做到和日期项目的时候使用频次较高的方法。

转载请注明原文地址: https://www.6miu.com/read-1750235.html

最新回复(0)