Joe
Joe

Reputation: 542

Current week monday date

In my case week start from Monday to Sunday.I want get current week Monday date. I using following code to get Monday date.

        Calendar c = Calendar.getInstance();
        c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        System.out.println("Date " + c.getTime());

It works fine for all days except Sunday,If current day is Sunday it will give next week Monday date.Is it possible get current week Monday date using java.util.Date/Calendar API even if it is Sunday.

Any help appreciated.

Upvotes: 0

Views: 3189

Answers (2)

Roland
Roland

Reputation: 23352

LocalDateTime thisWeeksMonday = LocalDateTime.now().with(DayOfWeek.MONDAY);

just in case that Java 8 is an option.

As stated in "Get date of first day of week based on LocalDate.now() in Java 8" your usage may differ.

Regarding Java <8 you need to set setFirstDayOfWeek as Jack mentioned. Just be sure that you set it before you alter your day of week, e.g.:

Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());

Upvotes: 1

Jack
Jack

Reputation: 3059

You can tell the Calendar class what day of the week should be considered as the first one. Try adding the following line:

c.setFirstDayOfWeek(Calendar.MONDAY);

Upvotes: 2

Related Questions