user236501
user236501

Reputation: 8648

Java - How to calculate the first and last day of each week

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

Upvotes: 20

Views: 70760

Answers (11)

Sibin
Sibin

Reputation: 561

    Calendar startCal = Calendar.getInstance();
    startCal.setTimeInMillis(startDate);
    Calendar endCal = Calendar.getInstance();
    endCal.setTimeInMillis(endDate);
    SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMM-yyyy");
    while (startCal.before(endCal)) {
        int weekNumber = startCal.get(Calendar.WEEK_OF_YEAR);
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
        cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
        Date sunday = cal.getTime();
        Log.d("sunday", "" + sdf.format(sunday));
        cal.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
        cal.set(Calendar.WEEK_OF_YEAR, weekNumber);
        Date saturday = cal.getTime();
        Log.d("saturday", "" + sdf.format(saturday));
        weekNumber = weekNumber + 1;
        startCal.set(Calendar.WEEK_OF_YEAR, weekNumber);

    }

Upvotes: 1

Gregor Koukkoullis
Gregor Koukkoullis

Reputation: 2305

With the new date and time API in Java 8 you would do:

LocalDate now = LocalDate.now();

// determine country (Locale) specific first day of current week
DayOfWeek firstDayOfWeek = WeekFields.of(Locale.getDefault()).getFirstDayOfWeek();
LocalDate startOfCurrentWeek = now.with(TemporalAdjusters.previousOrSame(firstDayOfWeek));

// determine last day of current week
DayOfWeek lastDayOfWeek = firstDayOfWeek.plus(6); // or minus(1)
LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(lastDayOfWeek));

// Print the dates of the current week
LocalDate printDate = startOfCurrentWeek;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE dd/MM/yyyy");
for (int i=0; i < 7; i++) {
    System.out.println(printDate.format(formatter));
    printDate = printDate.plusDays(1);
}

Upvotes: 13

Przemek Piotrowski
Przemek Piotrowski

Reputation: 7456

Java.time

Using java.time library built into Java 8:

import java.time.DayOfWeek;
import java.time.LocalDate;
import static java.time.temporal.TemporalAdjusters.previousOrSame;
import static java.time.temporal.TemporalAdjusters.nextOrSame;

LocalDate now = LocalDate.now(); # 2015-11-23
LocalDate first = now.with(previousOrSame(DayOfWeek.MONDAY)); # 2015-11-23
LocalDate last = now.with(nextOrSame(DayOfWeek.SUNDAY)); # 2015-11-29

You can iterate over DayOfWeek.values() to get all current week days

DayOfWeek.values(); # Array(MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY)
for (DayOfWeek day: DayOfWeek.values()) {
    System.out.print(first.with(nextOrSame(day)));
} # 2015-11-23, 2015-11-24, 2015-11-25, 2015-11-26, 2015-11-27, 2015-11-28, 2015-11-29

Upvotes: 10

Michael Piefel
Michael Piefel

Reputation: 19968

Simply setting the day of week does not seem to be reliable. Consider the following simple code:

Calendar calendar = Calendar.getInstance(Locale.GERMANY);
calendar.set(2011, Calendar.SEPTEMBER, 18);
System.out.printf("Starting day: %tF%n", calendar);

calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.printf("Last monday: %tF%n", calendar);
System.out.printf("First day of week: %d%n", calendar.getFirstDayOfWeek());

The result of running this program is:

Starting day: 2011-09-18
Last monday: 2011-09-19
First day of week: 2

In other words, it stepped forward in time. For a German locale, this is really not the expected answer. Note that the calendar correctly uses Monday as first day of the week (only for computing the week of the year, perhaps).

Upvotes: 6

Nivas
Nivas

Reputation: 18344

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);
}

Upvotes: 2

Jesper
Jesper

Reputation: 206786

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);
}

Upvotes: 44

Ant
Ant

Reputation: 4928

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

Upvotes: 0

Nikita Rybak
Nikita Rybak

Reputation: 68006

First day of this week.

    Calendar c = Calendar.getInstance();
    while (c.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
        c.add(Calendar.DATE, -1);
    }

Upvotes: 9

kgiannakakis
kgiannakakis

Reputation: 104168

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

Upvotes: 1

Sjoerd
Sjoerd

Reputation: 75588

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

Upvotes: 1

user334583
user334583

Reputation: 55

Yes. Use Joda Time

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

Upvotes: -1

Related Questions