获取当前月的第一天和最后一天;获取当前周的第一天和最后一天

来源:互联网 发布:北京seo网站排名优化 编辑:程序博客网 时间:2024/05/16 05:27

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 

        Calendar cale = Calendar.getInstance();  


//获取当前月的第一天

String firstday, lastday;

cale.setTime(new Date());
        cale.set(cale.get(Calendar.YEAR), cale.get(Calendar.MONTH), 1, 0, 0, 0);  
        firstday = format.format(cale.getTime());
        System.out.println("本月第一天是 : " + firstday); 
        
        //获取当前月的最后一天
        cale.setTime(new Date());
        cale.add(Calendar.MONTH, 1);  //当前月加上1个月,即第二个月
        cale.set(Calendar.DAY_OF_MONTH, 0);  //设置时间为第二个月的第一天减去一天
        cale.set(cale.get(Calendar.YEAR), cale.get(Calendar.MONTH), cale.get(Calendar.DAY_OF_MONTH), 23, 59, 59);  
        lastday = format.format(cale.getTime());
        System.out.println("本月最后一天是 : " + lastday); 
        
        //获取当前周的第一天
        String firstWeekday, lastWeekday; 
        cale.setTime(new Date());
        cale.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);//设置当前时间为周日
        cale.set(cale.get(Calendar.YEAR), cale.get(Calendar.MONTH), cale.get(Calendar.DAY_OF_MONTH), 0, 0, 0); 
        firstWeekday = format.format(cale.getTime());
        System.out.println("本周第一天是 : " + firstWeekday);
        
        //获取当前周的最后一天
        cale.setTime(new Date());
        cale.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);//设置当前时间为周日
        cale.set(cale.get(Calendar.YEAR), cale.get(Calendar.MONTH), cale.get(Calendar.DAY_OF_MONTH), 23, 59, 59); 
        lastWeekday = format.format(cale.getTime());
        System.out.println("本周最后一天是 : " + lastWeekday);

1 0
原创粉丝点击