Java gets the first and last day of this week and last week

Java get the first & last day of this week and last week.

code show as below:

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

/**
 * 周工具类
 */
public class WeekUtils {
    
    

    /**
     * 获取本周的第一天
     *
     * @return String
     **/
    public static String getThisWeekMonday() {
    
    
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.WEEK_OF_MONTH, 0);
        cal.set(Calendar.DAY_OF_WEEK, 2);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time) + " 00:00:00";
    }

    /**
     * 获取本周的最后一天
     *
     * @return String
     **/
    public static String getThisWeekSunday() {
    
    
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, cal.getActualMaximum(Calendar.DAY_OF_WEEK));
        cal.add(Calendar.DAY_OF_WEEK, 1);
        Date time = cal.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(time) + " 23:59:59";
    }

    /**
     * 获取上周的第一天
     *
     * @return
     * @throws Exception
     */
    public static String getPreviousWeekMonday() {
    
    
        int week = -1;
        int mondayPlus = getMondayPlus();

        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(5, mondayPlus + 7 * week);
        Date preMonday = currentDate.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(preMonday) + " 00:00:00";
    }

    /**
     * 获取上周的最后一天
     *
     * @return
     */
    public static String getPreviousWeekSunday() {
    
    
        int weeks = -1;
        int mondayPlus = getMondayPlus();
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.add(5, mondayPlus + weeks);
        Date preSunday = currentDate.getTime();
        return new SimpleDateFormat("yyyy-MM-dd").format(preSunday) + " 23:59:59";
    }

    public static int getMondayPlus() {
    
    
        Calendar cd = Calendar.getInstance();
        int dayOfWeek = cd.get(7) - 1;
        if (dayOfWeek == 1) {
    
    
            return 0;
        }
        return (1 - dayOfWeek);
    }

    public static void main(String[] args) throws Exception {
    
    
        System.out.println("获取上周的第一天:" + WeekUtils.getPreviousWeekMonday());
        System.out.println("获取上周的最后一天:" + WeekUtils.getPreviousWeekSunday());
        System.out.println("获取本周的第一天:" + WeekUtils.getThisWeekMonday());
        System.out.println("获取本周的最后一天:" + WeekUtils.getThisWeekSunday());
    }

}

insert image description here

– If you are hungry for knowledge, be humble if you are foolish.

Guess you like

Origin blog.csdn.net/qq_42402854/article/details/129885566