30

We have a utility that will run any day between Monday - Friday. It will update some number of files inside a Content Management Tool. The last modified date associated with that file should be, that week's monday's date. I wrote the following program to retrieve current week's monday's date. But I am still not sure whether this would work for all scenarios. Has anyone got a better solution ?

Calendar c = Calendar.getInstance();
c.setTime(new Date());
System.out.println(c.get(Calendar.DAY_OF_MONTH));
System.out.println(c.get(Calendar.DAY_OF_WEEK));
int mondayNo = c.get(Calendar.DAY_OF_MONTH)-c.get(Calendar.DAY_OF_WEEK)+2;
c.set(Calendar.DAY_OF_MONTH,mondayNo);
System.out.println("Date "+c.getTime());
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254
Shashank Kadne
  • 7,993
  • 6
  • 41
  • 54

9 Answers9

55

I would strongly recommend using Joda Time instead (for all your date/time work, not just this):

// TODO: Consider time zones, calendars etc
LocalDate now = new LocalDate();
LocalDate monday = now.withDayOfWeek(DateTimeConstants.MONDAY);
System.out.println(monday);

Note that as you've used Monday here, which is the first day of the week in Joda Time, this will always return an earlier day (or the same day). If you chosen Wednesday (for example), then it would advance to Wednesday from Monday or Tuesday. You can always add or subtract a week if you need "the next Wednesday" or "the previous Wednesday".

EDIT: If you really want to use java.util.Date/Calendar, you can use:

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

You can use Calendar.setFirstDayOfWeek to indicate whether a week is Monday-Sunday or Sunday-Saturday; I believe setting the day of the week will stay within the current week - but test it.

Reaver
  • 323
  • 3
  • 21
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    Is this not possible with just Java api's ? We use a CMS tool, where adding a new jar would require a deployment change. – Shashank Kadne Feb 16 '12 at 08:44
  • 2
    @ShashankKadne: It's *possible*, sure - but it's *horrible*. If you do any significant amount of date-based work, the benefits of using Joda Time will *far* outweigh the brief cost. – Jon Skeet Feb 16 '12 at 08:45
  • 1
    @ShashankKadne: I've edited my answer with the java.util.Calendar code... but I'd still recommend using Joda Time instead. – Jon Skeet Feb 16 '12 at 08:50
  • @jon Skeet : (+1) This code works! But if we select any sunday, it wud give us the next week's monday's date, which is still yet to come. Can't we get the previous monday, everytime ? – Shashank Kadne Feb 16 '12 at 09:28
  • We can add c.setFirstDayOfWeek(Calendar.MONDAY); to your code! – Shashank Kadne Feb 16 '12 at 09:29
  • I dint see your edit previously..Thnks I ll use this solution. – Shashank Kadne Feb 16 '12 at 09:33
  • 3
    It's not working on sunday. It will give the next week's monday. – acsadam0404 Sep 07 '14 at 09:32
  • @adam0404: With which of the examples? Note that for the java.util.Calendar example, I specify how you'd change the first day of the week if you need to. – Jon Skeet Sep 07 '14 at 12:37
  • As Jon Skeet explained, this Answer's code may go backward or forward in time. If you always want to use Joda-Time to find the *next* Monday (future only, not past), see [my answer](http://stackoverflow.com/a/29724887/642706) on a similar Question. – Basil Bourque Apr 19 '15 at 02:25
  • "Calendar.setFirstDayOfWeek" Thank you so much! – 0xRLA Oct 02 '16 at 11:35
31

tl;dr

LocalDate previousMonday = 
    LocalDate.now( ZoneId.of( "America/Montreal" ) )
             .with( TemporalAdjusters.previous( DayOfWeek.MONDAY ) );

java.time

Both the java.util.Calendar class and the Joda-Time library have been supplanted by the java.time framework built into Java 8 and later. See Oracle Tutorial. Much of the java.time functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP. With modern Android tooling and its "API desugaring", you need not add any library.

The java.time.LocalDate class represents a date-only value without time-of-day and without time zone.

Determining today's date requires a time zone, a ZoneId.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );

The TemporalAdjuster interface (see Tutorial) is a powerful but simple way to manipulate date-time values. The TemporalAdjusters class (note the plural) implements some very useful adjustments. Here we use previous( DayOfWeek).

The handy DayOfWeek enum makes it easy to specify a day-of-week.

LocalDate previousMonday = today.with( TemporalAdjusters.previous( DayOfWeek.MONDAY ) );

If today is Monday, and you want to use today rather than a week ago, call previousOrSame.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
6

The following will work, including wrapping months:

Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.setTime(new Date());
int today = c.get(Calendar.DAY_OF_WEEK);
c.add(Calendar.DAY_OF_WEEK, -today+Calendar.MONDAY);
System.out.println("Date "+c.getTime());

If, however, you edit your application on a Sunday (eg. Sunday 12 Feb), the date will be for the following Monday. Based on your requirements (the app will only run Monday thru Friday), this should not pose a problem.

radimpe
  • 3,197
  • 2
  • 27
  • 46
  • (+1) for making it work for that extreme condition. But I ll go with @Jon's solution, as his code is smaller than mine. ;) – Shashank Kadne Feb 16 '12 at 09:31
  • FYI, the terribly troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Feb 09 '19 at 07:48
2

As Jon suggested, the calendar.set method works... I've tested it both in the case of a monday in same month and in another month using following snippet :

Calendar c = Calendar.getInstance();
//ensure the method works within current month
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());
//go to the 1st week of february, in which monday was in january
c.set(Calendar.DAY_OF_MONTH, 1);
System.out.println("Date " + c.getTime());
//test that setting day_of_week to monday gives a date in january
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());
//same for tuesday
c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
System.out.println("Date " + c.getTime());

The results:

Date Mon Feb 13 10:29:41 CET 2012
Date Wed Feb 01 10:29:41 CET 2012
Date Mon Jan 30 10:29:41 CET 2012
Date Tue Jan 31 10:29:41 CET 2012
Simon Baslé
  • 27,105
  • 5
  • 69
  • 70
1

What about using Joda Time library... Take look at this answer...

Community
  • 1
  • 1
PrimosK
  • 13,848
  • 10
  • 60
  • 78
  • Is this not possible with just Java api's ? We use a CMS tool, where adding a new jar would require a deployment change. – Shashank Kadne Feb 16 '12 at 08:44
  • Try to look at Joda Time [source](https://github.com/JodaOrg/joda-time).. Maybe you could find out the best way to implement such a feature with Java api's... – PrimosK Feb 16 '12 at 08:46
0

in case you don't want to use Joda Time you can do like this to find the weeks -> (works on Android)

public static ArrayList<String> getWeeks(int month) {

ArrayList<String> arrayListValues = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("MMMM d");

Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.MONTH, month);

int day = calendar.get(Calendar.DAY_OF_WEEK);
while (day != 1) {
  calendar.add(Calendar.DATE, 1);
  day = calendar.get(Calendar.DAY_OF_WEEK);
}

calendar.add(Calendar.DATE, -14);
String y1 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 6);
String y2 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 1);
arrayListValues.add(y1 + " - " + y2);

 y1 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 6);
 y2 = sdf.format(calendar.getTime());
calendar.add(Calendar.DATE, 1);
arrayListValues.add(y1 + " - " + y2);



for (int i = 0; i < 10; i++) {

  y1 = sdf.format(calendar.getTime());
  calendar.add(Calendar.DATE, 6);
  y2 = sdf.format(calendar.getTime());
  calendar.add(Calendar.DATE, 1);
  arrayListValues.add(y1 + " - " + y2);
}

return arrayListValues;
}
OWADVL
  • 10,704
  • 7
  • 55
  • 67
0

For version Android 6.0 or grater use:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
int day = 1, month = 7, year = 2018;
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
c.set(year, month, day);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);  //change de day to monday
String dateMonday= sdf.format(c.getTime());

For version Android 5.1 or less it does not work appropriately, I created my own method.

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
int day = 1, month = 7, year = 2018;
Calendar c = Calendar.getInstance();
c.setFirstDayOfWeek(Calendar.MONDAY);
//set the date with your date or the current date c.set(new Date());
c.set(year, month, day);

int diaSemana = c.get(Calendar.DAY_OF_WEEK);
for (int i = 0; i < 7; i++) {
 if (diaSemana != Calendar.MONDAY) {
     day--;
     c.set(year, month, day);
     diaSemana = c.get(Calendar.DAY_OF_WEEK);
     if (diaSemana == Calendar.MONDAY) break;
  } else {
    break;
 }
}
String dateMonday= sdf.format(c.getTime());
Adolfo Rangel
  • 71
  • 1
  • 3
  • 1
    FYI, the troublesome old date-time classes such as `java.util.Date`, `java.util.Calendar`, and `java.text.SimpleDateFormat` are now legacy, supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. Most of the *java.time* functionality is back-ported to Java 6 & Java 7 in the [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/) project. Further adapted for earlier Android (<26) in [***ThreeTenABP***](https://github.com/JakeWharton/ThreeTenABP). See [*How to use ThreeTenABP…*](http://stackoverflow.com/q/38922754/642706). – Basil Bourque Feb 09 '19 at 01:01
  • For Android versions 8 and 9 (API level 26 and higher) java.time is built in, there’s no reason whatsoever to use anything else. For versions 5, 6 and 7 I join @BasilBourque in recommending ThreeTenABP so you can still use java.time. Not that the question asked about Android specifically. – Ole V.V. Feb 09 '19 at 06:56
0

Kotlin code. Works in older android versions

    val c = Calendar.getInstance()
    c.time = Date()
    
    while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
        c.add(Calendar.DAY_OF_WEEK, -1)
    }
user3561494
  • 2,164
  • 1
  • 20
  • 33
-2

It won't work if the currents week monday is the month before... For example if today is Friday 1st of June... You should probably rather use the roll method...

pgras
  • 12,614
  • 4
  • 38
  • 46