java 获取当前月第一天 计算当月最后一天 获取年月

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

public class DateHelper {
    /**
     * 当前月第一天
     * @return
     */
    public static String getFirstDayOfMonth(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Calendar lastDate = Calendar.getInstance();
        lastDate.set(Calendar.DATE,1);//设为当前月的1 号
        lastDate.add(Calendar.MONTH,-1);//加一个月,变为下月的1 号
        return sdf.format(lastDate.getTime());
    }

    /**
     * 计算当月最后一天
     * @return
     */
    public static String getLastDayOfMonth(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd 23:59:59");
        Calendar lastDate = Calendar.getInstance();
        lastDate.set(Calendar.DATE,1);//设为当前月的1 号
        lastDate.add(Calendar.DATE,-1);//减去一天,变为当月最后一天
        return sdf.format(lastDate.getTime());
    }

    /**
     * 获取年月
     * @return
     */
    public static String getThisYearAndMonth(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        return sdf.format(getFirstDayOfMonth());
    }

}
;

Popular Programs