Java根据一个指定的年月获取此月份的月初和月末

一、根据指定年月获取月初和月末

/**
	 * 根据年月获取月初第一天日期
	 * @param year
	 * @param month
	 * @return
	 */
	public static String getFirstDay(int year,int month,String format) {
    	Calendar calendar = Calendar.getInstance();
    	calendar.set(Calendar.YEAR, year);
    	calendar.set(Calendar.MONTH, month-1);
    	calendar.set(Calendar.DAY_OF_MONTH, 1);
    	
    	Date startDate = calendar.getTime();
		
    	SimpleDateFormat sdf = new SimpleDateFormat(format);
    	String formattedStartDate = sdf.format(startDate);
    	
		return formattedStartDate;
    }
	
	
	/**
	 * 根据年月获取月末最后一天日期
	 * @param year
	 * @param month
	 * @return
	 */
	public static String getLastDay(int year,int month,String format) {
    	Calendar calendar = Calendar.getInstance();
    	calendar.set(Calendar.YEAR, year);
    	calendar.set(Calendar.MONTH, month);
		
    	calendar.set(Calendar.DAY_OF_MONTH, 1);
    	
    	calendar.add(Calendar.DAY_OF_MONTH, -1);
    	Date endDate = calendar.getTime();
		
    	SimpleDateFormat sdf = new SimpleDateFormat(format);
    	String formattedEndDate = sdf.format(endDate);
		
		return formattedEndDate;
    }

二、根据当前系统日期获取月初和月末

    /**
     * 获取本月最后一天
     * @return
     */
    public static String getLastDay(String format) {
    	Calendar cale = Calendar.getInstance();

    	int lastDay = cale.getActualMaximum(Calendar.DAY_OF_MONTH);//获取月最大天数
    	cale.set(Calendar.DAY_OF_MONTH, lastDay);//设置日历中月份的最大天数
    	SimpleDateFormat sdf = new SimpleDateFormat(format);//格式化日期yyyy-MM-dd
    	String lastDayOfMonth = sdf.format(cale.getTime());
    	return lastDayOfMonth;
    }
    
    /**
     * 获取本月第一天
     * @return
     */
    public static String getFirstDay(String format) {
    	Calendar cale = Calendar.getInstance();

    	int lastDay = cale.getActualMinimum(Calendar.DAY_OF_MONTH);//获取月最大天数
    	cale.set(Calendar.DAY_OF_MONTH, lastDay);//设置日历中月份的最大天数
    	SimpleDateFormat sdf = new SimpleDateFormat(format);//格式化日期yyyy-MM-dd
    	String lastDayOfMonth = sdf.format(cale.getTime());
    	return lastDayOfMonth;
    }

你可能感兴趣的:(java,java)