根据当前日期求上周一,上周日,上上周一,上周日的日期(详细解释代码)


前言:最近写项目,需要求这四个指标,就写了下这个方法。

public static String getLastMondayAndSunday(String day, int number) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String lastLastMonday = null;
        try {
            Date date1 = sdf.parse(day);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date1);
            int dayTime = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            if(dayTime == 0){
                dayTime = 7;
            }
            Date date2 = new Date(date1.getTime() - 24*60*60*1000*(dayTime + number));
            lastLastMonday = sdf.format(date2);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            return lastLastMonday;
        }
    }

作用:

根据当前的日期求上周一,上周天,上上周一,上上周日的日期(例如今天是周二,则求的是上周一,上周日的日期)。如果你完全理解了这个方法,它求的不仅仅局限于这几个指标。

用法:

传入日期和参数。

上上周一:13     上上周日:7     上周一:6    上周日:0

例如:求上上周一的日期     

getLastMondayAndSunday(“2018-03-22”, 13)

解释:

结论:

可以理解透了,自己可以传入对应的number求自己想要的结果。

猜你喜欢

转载自blog.csdn.net/Poppy_Evan/article/details/79650887