java Calendar获取某个时间上个月的时间

java8的时间api很好用,但有的场景用Calendar也是很合适的

 

 /**
     * 从当前时间获取上个月的第一天和最后一天
     */
    private void getPreMonthDate(String startDate) throws Exception {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = getPreMonth(startDate);

        //获取某月最小天数
        int firstDay = c.getActualMinimum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最小天数
        c.set(Calendar.DAY_OF_MONTH, firstDay);
        // 上个月第一天
        String startTime = format.format(c.getTime());

        
        Calendar c2 = getPreMonth(startDate);
        int lastDay = c2.getActualMaximum(Calendar.DAY_OF_MONTH);
        c2.set(Calendar.DAY_OF_MONTH, lastDay);
        String endTime = format.format(c2.getTime());


    }

    /**
     * 从当前时间"yyyy-MM-dd"格式获取上个月的时间
     */
    private Calendar getPreMonth(String startDate) throws Exception{
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        Date date = format.parse(startDate);
        c.setTime(date);
        c.add(Calendar.MONTH, -1);
        return c;
    }
获取上周的时间也是一个道理
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
Date date = format.parse("2020-05-01");
c.setTime(date);
c.add(Calendar.DATE, -7);
format.format(c.getTime());

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章