代码改变世界

JAVA获取上月、本月的第一天和最后一天

2023-06-07 11:47  猎手家园  阅读(2380)  评论(0编辑  收藏  举报

1、获取【上个月】第一天和上个月最后一天

/**
 * 获取上个月第一天和上个月最后一天
 *
 * @throws ParseException
 */
public static Map<String, String> getLastOneMonthDay() {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Map<String, String> map = new HashMap<>();
    
    // 上月起始
    Calendar lastMonthFirstDateCal = Calendar.getInstance();
    lastMonthFirstDateCal.add(Calendar.MONTH, -1);
    lastMonthFirstDateCal.set(Calendar.DAY_OF_MONTH, 1);
    String lastMonthFirstTime = format.format(lastMonthFirstDateCal.getTime());
    System.out.println("上月起始:" + lastMonthFirstTime);
    
    // 上月末尾
    Calendar lastMonthEndDateCal = Calendar.getInstance();
    lastMonthEndDateCal.add(Calendar.MONTH, -1);
    lastMonthEndDateCal.set(Calendar.DAY_OF_MONTH, lastMonthEndDateCal.getActualMaximum(Calendar.DAY_OF_MONTH));
    String lastMonthEndTime = format.format(lastMonthEndDateCal.getTime());
    System.out.println("上月末尾:" + lastMonthEndTime);
    
    map.put("beginDate", lastMonthFirstTime);
    map.put("endDate", lastMonthEndTime);
    return map;
}

 

2、获取【当月】第一天和上个月最后一天

/**
 * 获取当月第一天和上个月最后一天
 *
 * @throws ParseException
 */
public static Map<String, String> getNowOneMonthDay() {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Map<String, String> map = new HashMap<>();
    
    // 本月起始
    Calendar thisMonthFirstDateCal = Calendar.getInstance();
    thisMonthFirstDateCal.set(Calendar.DAY_OF_MONTH, 1);
    String thisMonthFirstTime = format.format(thisMonthFirstDateCal.getTime());
    System.out.println("本月起始:" + thisMonthFirstTime);
    
    // 本月末尾
    Calendar thisMonthEndDateCal = Calendar.getInstance();
    thisMonthEndDateCal.set(Calendar.DAY_OF_MONTH, thisMonthEndDateCal.getActualMaximum(Calendar.DAY_OF_MONTH));
    String thisMonthEndTime = format.format(thisMonthEndDateCal.getTime());
    System.out.println("本月末尾:" + thisMonthEndTime);

    map.put("beginDate", thisMonthFirstTime);
    map.put("endDate", thisMonthEndTime);
    return map;
}