java获取当月第一天时间、当月最后一天时间、上月第一天时间、上月最后一天时间

java获取当月第一天时间、当月最后一天时间、上月第一天时间、上月最后一天时间

import java.text.SimpleDateFormat;
import java.util.Calendar;
public class test {
    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        // 本月起始
        Calendar thisMonthFirstDateCal = Calendar.getInstance();
        thisMonthFirstDateCal.set(Calendar.DAY_OF_MONTH, 1);
        String thisMonthFirstTime = format.format(thisMonthFirstDateCal.getTime()) + " 00:00:00";
        System.out.println("本月起始:" + thisMonthFirstTime);
        // 本月末尾
        Calendar thisMonthEndDateCal = Calendar.getInstance();
        thisMonthEndDateCal.set(Calendar.DAY_OF_MONTH, thisMonthEndDateCal.getActualMaximum(Calendar.DAY_OF_MONTH));
        String thisMonthEndTime = format.format(thisMonthEndDateCal.getTime()) + " 23:59:59";
        System.out.println("本月末尾:" + thisMonthEndTime);
        // 上月起始
        Calendar lastMonthFirstDateCal = Calendar.getInstance();
        lastMonthFirstDateCal.add(Calendar.MONTH,-1);
        lastMonthFirstDateCal.set(Calendar.DAY_OF_MONTH, 1);
        String lastMonthFirstTime = format.format(lastMonthFirstDateCal.getTime()) + " 00:00:00";
        System.out.println("上月起始:" + lastMonthFirstTime);
        // 上月末尾
        Calendar lastMonthEndDateCal = Calendar.getInstance();
        lastMonthEndDateCal.add(Calendar.MONTH,-1);
        lastMonthEndDateCal.set(Calendar.DAY_OF_MONTH, lastMonthEndDateCal.getActualMaximum(Calendar.DAY_OF_MONTH));
        String lastMonthEndTime = format.format(lastMonthEndDateCal.getTime()) + " 23:59:59";
        System.out.println("上月末尾:" + lastMonthEndTime);

java获取当前时间本周第一天跟本周最后一天

* 获取当前周的周一的日期 * @param date 传入当前日期 * @return public static Date getThisWeekMonday(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); // 获得当前日期是一个星期的第几天 int dayWeek = cal.get(Calendar.DAY_OF_WEEK); if (1 == dayWeek) { cal.add(Calendar.DAY_OF_MONTH, -1); // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一 cal.setFirstDayOfWeek(Calendar.MONDAY); // 获得当前日期是一个星期的第几天 int day = cal.get(Calendar.DAY_OF_WEEK); cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day); cal.set(Calendar.HOUR_OF_DAY,0); cal.set(Calendar.MINUTE,0); cal.set(Calendar.SECOND,0); cal.set(Calendar.MILLISECOND,0); return cal.getTime(); * 获取当前周的周天的日期 * @param date 传入当前日期 * @return public static Date getThisWeekSunday(Date date) { Calendar cal = Calendar.getInstance(); cal.setTime(date); // 获得当前日期是一个星期的第几天 int dayWeek = cal.get(Calendar.DAY_OF_WEEK); if (1 == dayWeek) { cal.add(Calendar.DAY_OF_MONTH, -1); // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一 cal.setFirstDayOfWeek(Calendar.MONDAY); // 获得当前日期是一个星期的第几天 int day = cal.get(Calendar.DAY_OF_WEEK); int first = cal.getFirstDayOfWeek(); // 计算周天的日期 cal.add(Calendar.DAY_OF_WEEK, first - day + 6); cal.set(Calendar.HOUR_OF_DAY,23); cal.set(Calendar.MINUTE,59);