• Post Reply Bookmark Topic Watch Topic
  • New Topic

Getting the day of Monday given the date of other day in that week  RSS feed

 
vikas Chitte
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I have a instance of Calendar which is set to say
day = 25
month = 7
year = 2006

Now the day comes to be Friday.

I need to extract the date of the immediate previous Monday, which in this case is the 21st.

Is there some way to do that combing given functions and constants of the Calendar class???
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16058
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ofcourse there is, and it's very simple.

You need to use the set(...) method in class Calendar. The field you want to set is Calendar.DAY_OF_WEEK and you'll want to set it to Calendar.MONDAY.

[ August 10, 2006: Message edited by: Jesper Young ]
 
vikas Chitte
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i can't change the calendar object.

now a obvious way out is by looping backwards untill the day != Calendar.MONDAY.

What i want to know is that is there any way to avoid that looping using combinations of funtions and the constants.
 
Lanny Gilbert
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just clone the Calendar you have using the clone() method and perform what the previous poster said on the cloned object. That'll give you your Monday and it will keep your original Calendar unchanged.
 
Lanny Gilbert
Ranch Hand
Posts: 134
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's some code I tried that works just fine.

Calendar cal = Calendar.getInstance();

// Set the calendar to August 4th, 2006
cal.set(2006, Calendar.AUGUST, 4);

Calendar clonedCal = (Calendar)cal.clone();


clonedCal.set(Calendar.WEEK_OF_MONTH,
cal.get(Calendar.WEEK_OF_MONTH));

clonedCal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

System.out.println(clonedCal.getTime());
 
Jeroen T Wenting
Ranch Hand
Posts: 1847
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by vikas Chitte:
i can't change the calendar object.


Ah, a homework question. That's the only style of question that would have such a requirement

Just create another Calendar based on the contents of the one you have and voila
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!