0

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.

Joe
  • 550
  • 2
  • 11
  • 21

2 Answers2

2

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);
Jack
  • 2,937
  • 5
  • 34
  • 44
1
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());
Community
  • 1
  • 1
Roland
  • 22,259
  • 4
  • 57
  • 84
  • Ya,I know this works in java 8 but I am using older version java 1.7. – Joe Apr 13 '17 at 09:08
  • 1
    what a pity :-/ – Roland Apr 13 '17 at 09:10
  • No I tried this thing before no use..Still I am getting same result. – Joe Apr 13 '17 at 09:33
  • hmmm... I wonder whether you expect something different... could you please add examples what you expect for which date and what you got instead? that way you also don't risk that it gets closed as duplicate. – Roland Apr 13 '17 at 09:37
  • 1
    Most of the java.time functionality built into Java 8 & 9 is back-ported to Java 6 & 7 in the *ThreeTen-Backport* project. Further adapted for Android in the *ThreeTenABP* project. – Basil Bourque Apr 13 '17 at 18:34