简体   繁体   中英

Java : How to get Monday's date of the current week without the time and subtract it by 1 day

What would i like to do is get the Monday's date from the current week and subtract it by 1 day. I do not need the time with the date. I've tried below code but it gives me Sunday's date instead of Monday and also time is getting included with the date.Thanks.

Date date = new Date();
        System.out.println(date);
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
        c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);

        Date weekStart = c.getTime();
        System.out.println(weekStart);

I suggest using the JDK8 Date-time APIs which largely simplify these calculations.

LocalDate dt = LocalDate.now()
                        .with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
                        .minusDays(1);
System.out.println(dt);

The above code gets the current date and adjust it to the current week's Monday or previous week's Monday if the current day is a Sunday. Then subtract 1 day from it, to give the Sunday's date. As LocalDate API deals with only dates, there isn't any need to take care of the time part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM