Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java : Get any day in a week from Calendar

Tags:

java

calendar

Using Calendar I can get the week, year and all details for the current day. How can I navigate to a particualr day in that week?

Say, calendar.get(Calendar.DAY_OF_WEEK); returns 3, which means a Tuesday. Now, I want to go to say Friday for that week or any other day in that week. How can I do that?

Thanks for your replies. I think I need to make the scenario more clear. Basically, I am trying to disable email alerts in my system during specified period. I get values like: disableStart = "FRIDAY-19:00" disableEnd = "SUNDAY-19:00"

Now, i need to verify if email should be sent at a particular time. e.g. if today = Thursday any time, send email but, if today = Saturday any time can't send as per values above.

like image 580
Anubhav Anand Avatar asked Oct 08 '10 13:10

Anubhav Anand


3 Answers

If I understand correctly you can use the Calendar.set(Field, value) method.

SimpleDateFormat f = new SimpleDateFormat("dd-MM-yyyy");
Calendar c = Calendar.getInstance();
System.out.println(c.get(Calendar.DAY_OF_WEEK));
System.out.println(f.format(c.getTime()));
c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
System.out.println(c.get(Calendar.DAY_OF_WEEK));
System.out.println(f.format(c.getTime()));

Produces the output

6
08-10-2010
3
05-10-2010
like image 146
Kevin D Avatar answered Sep 22 '22 16:09

Kevin D


Calendar c = Calendar.getInstance();
Date date = new Date();
c.setTime(date);
System.out.println("Today:  " + c.getTime());
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("MONDAY: " + c.getTime());
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
System.out.println("TUESDAY: " + c.getTime());
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
System.out.println("WEDNESDAY: " + c.getTime());
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
System.out.println("THURSDAY: " + c.getTime());
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("FRIDAY: " + c.getTime());
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("SATURDAY: " + c.getTime());
c.setTime(date);
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("SUNDAY: " + c.getTime());

Gives:

Today:  Fri Oct 08 15:45:14 CEST 2010
MONDAY: Mon Oct 04 15:45:14 CEST 2010
TUESDAY: Tue Oct 05 15:45:14 CEST 2010
WEDNESDAY: Wed Oct 06 15:45:14 CEST 2010
THURSDAY: Thu Oct 07 15:45:14 CEST 2010
FRIDAY: Fri Oct 08 15:45:14 CEST 2010
SATURDAY: Sat Oct 09 15:45:14 CEST 2010
SUNDAY: Sun Oct 10 15:45:14 CEST 2010

Which seams to mean that, at least on my system, the weeks starts on monday.

like image 23
Maurice Perry Avatar answered Sep 19 '22 16:09

Maurice Perry


cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);

like image 41
jarnbjo Avatar answered Sep 22 '22 16:09

jarnbjo