1. 程式人生 > >獲得指定月的最後一天和第一天

獲得指定月的最後一天和第一天

  獲取指定年月的第一天

/**
     * 獲取指定年月的第一天
     * @param year
     * @param month
     * @return
	 * @throws ParseException 
     */
    @SuppressWarnings("unused")
	private String getFirstDayOfMonth1(String date) throws ParseException { 
    	//格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date curDate = new Date();
        
        if(StringUtils.isNotBlank(date)){
        	curDate = sdf.parse(date);
        }
        
        Calendar cal = Calendar.getInstance(); 
        
        cal.setTime(curDate);
        
        //獲取某月最小天數
        int firstDay = cal.getMinimum(Calendar.DATE);
        //設定日曆中月份的最小天數 
        cal.set(Calendar.DAY_OF_MONTH,firstDay);  
        
        return df.format(cal.getTime());  
    }

 獲取指定年月的最後一天

/**
     * 獲取指定年月的最後一天
     * @param year
     * @param month
     * @return
     * @throws ParseException 
     */
     @SuppressWarnings("unused")
	private  String getLastDayOfMonth1(String date) throws ParseException {  
    	//格式化日期
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM"); 
         SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
         Calendar cal = Calendar.getInstance();   
         
         Date curDate = new Date();
         
         if(StringUtils.isNotBlank(date)){
         	curDate = sdf.parse(date);
         }
         
         cal.setTime(curDate);
         //獲取某月最大天數
         int lastDay = cal.getActualMaximum(Calendar.DATE);
         //設定日曆中月份的最大天數  
         cal.set(Calendar.DAY_OF_MONTH, lastDay);  
          
         return df.format(cal.getTime());
     }