views:

511

answers:

7

I'm trying to create a weekly calendar that looks like this: http://dhtmlx.com/docs/products/dhtmlxScheduler/sample_basic.html

How can I calculate every week date? For example, this week is:

Monday - Sunday
7 June, 8 June, 9 June, 10 June, 11 June, 12 June, 13 June

A: 

Yes. Use Joda Time

http://joda-time.sourceforge.net/

A: 

If you know which day it is (Friday) and the current date (June 11), you can calculate the other days in this week.

Sjoerd
A: 

I recommend that you use Joda Time library. Gregorian Calendar class has weekOfWeekyear and dayOfWeek methods.

kgiannakakis
A: 

First day of this week.

    Calendar c = Calendar.getInstance();
    while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
        c.add(Calendar.DATE, -1);
    }
Nikita Rybak
It's not necessary to step back to Monday day by day, you can just `c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);` to set the calendar to Monday of the current week (see my answer).
Jesper
A: 

The algorithm you're looking for (calculating the day of the week for any given date) is "Zeller's Congruence". Here's a Java implementation:

http://technojeeves.com/joomla/index.php/free/57-zellers-congruence

Ant
A: 

I guess this does what you want:

// Get calendar set to current date and time
Calendar c = Calendar.getInstance();

// Set the calendar to monday of the current week
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

// Print dates of the current week starting on Monday
DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy");
for (int i = 0; i < 7; i++) {
    System.out.println(df.format(c.getTime()));
    c.add(Calendar.DATE, 1);
}
Jesper
Thank you this is what I want, if i want previous button can get last week date any idea?
Class `Calendar` contains methods for date arithmetic. To move it back a week (7 days), do `c.add(Calendar.DATE, -7);`, for example.
Jesper
Thank You very much appreaciate your help .
Instead of hardcoding Calendar.MONDAY as the first day of the week, you should use `Calendar#getFirstDayOfWeek()` instead, since the scope of a week is locale dependent.
jarnbjo
@Downvoter: Please explain why you downvoted.
Jesper
How to downvoted?
@newbie123: there are arrows above and below the number at the top left of the post. See the FAQ: http://stackoverflow.com/faq
Jesper
sorry not mean to downvoted your answer, maybe i accidentally clicked, i didn't notice that. had changed it back.
+1  A: 

You can build up on this: The following code prints the first and last dates of each week for 15 weeks from now.

Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
for(int i=0; i<15; i++)
{
    System.out.print("Start Date : " + c.getTime() + ", ");
    c.add(Calendar.DAY_OF_WEEK, 6);
    System.out.println("End Date : " + c.getTime());
    c.add(Calendar.DAY_OF_WEEK, 1);
}
Nivas