didikee - 博客园

获取本月 第一天 最后一天 上月第一天 最后一天

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Test3 {
    //测试
    public static void main(String[] args) {
        Test3 test3=new Test3();
        test3.preMonth();
        test3.thisMonth();
    }

    //代码

    SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar=Calendar.getInstance();
    /**
     * calendar输出结果如下:
     [id="Asia/Shanghai",
     offset=28800000,
     YEAR=2019,
     MONTH=8,
     WEEK_OF_YEAR=38,
     WEEK_OF_MONTH=3,
     DAY_OF_MONTH=19,
     DAY_OF_YEAR=262,
     DAY_OF_WEEK=5,
     DAY_OF_WEEK_IN_MONTH=3,
     HOUR_OF_DAY=9,MINUTE=14,SECOND=42,MILLISECOND=308,ZONE_OFFSET=28800000]
     */
    public void preMonth(){
        //获取前一个月的第一天
        calendar.add(Calendar.MONTH,-1);
        calendar.set(Calendar.DAY_OF_MONTH,1);
        String fistDay = formatter.format(calendar.getTime());
        System.out.println("上个月的第一天:"+fistDay);

        //获取前一个月最后一天
        //获取当前日期:月日
        Calendar calendar1 = Calendar.getInstance();
        //获取这个月的前一天,即上个月的最后一天.
        calendar1.set(Calendar.DAY_OF_MONTH,0);//设置为1号,当前日期既为本月第一天
        //转换为自己想要的日期格式
        String lastDay = formatter.format(calendar1.getTime());
        System.out.println("上个月的最后一天:"+lastDay);
    }

    public void thisMonth(){
        //获取本月的第一天
        Calendar calendar0 = Calendar.getInstance();
        calendar0.set(Calendar.DAY_OF_MONTH,1);
        String firstDay = formatter.format(calendar0.getTime());
        System.out.println("本月的第一天:"+firstDay);

        //本月的最后一天方法一:
        Calendar calendar1 = Calendar.getInstance();
        calendar1.set(Calendar.DAY_OF_MONTH,calendar1.getActualMaximum(Calendar.DAY_OF_MONTH));
        String lastDay1 = formatter.format(calendar1.getTime());
        System.out.println("当前月的最后一天"+lastDay1);

        //本月的最后一天方法二:
        Calendar calendar2 = Calendar.getInstance();
        calendar2.add(Calendar.MONTH,+1);
        calendar2.set(Calendar.DAY_OF_MONTH,0);
        String lastDay2 = formatter.format(calendar2.getTime());
        System.out.println("当前月的最后一天"+lastDay2);
    }
    
}

  

posted @ 2019-09-19 10:04  排雷兵  阅读(414)  评论(0编辑  收藏  举报
//粒子吸附特效
  
*
*
*
*
*
*
*
*
*
*
*
*
*