数据查询: 传递的时间是字符串时间(202107) 需要拿到前两个月的时间(也就是要以202105的时间去查询数据)
两种解决方案:
在sql语句层面取到指定的时间来进行业务处理
select to_date('20161230','yyyymmdd')-to_date('20161201','yyyymmdd') from dual;
通过Java代码层面, 首先可以写个方法, 拿到上个月的时间, 然后再调用一下, 就可以拿到上上个月的时间;
package com.biostime.merchant.wx; import com.biostime.merchant.wx.exception.MerchantWxException; import org.apache.commons.lang.StringUtils; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * @author TongHu * @date 2021/7/30 - 14:09 */ public class TestDate { public static void main(String[] args)throws Exception { String lastYearMonthByYearMonth = getLastYearMonthByYearMonth(null); System.out.println("lastYearMonthByYearMonth = " + lastYearMonthByYearMonth); String lastYearMonthByYearMonth1 = getLastYearMonthByYearMonth(lastYearMonthByYearMonth); System.out.println("lastYearMonthByYearMonth1 = " + lastYearMonthByYearMonth1); } public static String getLastYearMonthByYearMonth(String yearMonth) throws Exception{ SimpleDateFormat format = new SimpleDateFormat("yyyyMM"); Date date = null; try { if (StringUtils.isNotBlank(yearMonth)) { date = format.parse(yearMonth); } else { date = new Date(); } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); // 设置为当前时间 calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月 date = calendar.getTime(); String accDate = format.format(date); return accDate; } catch (Exception e) { throw new MerchantWxException("日期格式有误"); } } } package com.biostime.merchant.wx; import com.biostime.merchant.wx.exception.MerchantWxException; import org.apache.commons.lang.StringUtils; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; /** * @author TongHu * @date 2021/7/30 - 14:09 */ public class TestDate { public static void main(String[] args)throws Exception { String lastYearMonthByYearMonth = getLastYearMonthByYearMonth(null); System.out.println("lastYearMonthByYearMonth = " + lastYearMonthByYearMonth); String lastYearMonthByYearMonth1 = getLastYearMonthByYearMonth(lastYearMonthByYearMonth); System.out.println("lastYearMonthByYearMonth1 = " + lastYearMonthByYearMonth1); } public static String getLastYearMonthByYearMonth(String yearMonth) throws Exception{ SimpleDateFormat format = new SimpleDateFormat("yyyyMM"); Date date = null; try { if (StringUtils.isNotBlank(yearMonth)) { date = format.parse(yearMonth); } else { date = new Date(); } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); // 设置为当前时间 calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月 date = calendar.getTime(); String accDate = format.format(date); return accDate; } catch (Exception e) { throw new MerchantWxException("日期格式有误"); } } }