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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chinafire525/article/details/85160968
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());
    }

}

猜你喜欢

转载自blog.csdn.net/chinafire525/article/details/85160968
今日推荐