20

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

MPelletier
  • 16,256
  • 15
  • 86
  • 137
user236501
  • 8,538
  • 24
  • 85
  • 119

11 Answers11

45

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
  • 202,709
  • 46
  • 318
  • 350
  • Thank you this is what I want, if i want previous button can get last week date any idea? – user236501 Jun 11 '10 at 14:07
  • Class `Calendar` contains methods for date arithmetic. To move it back a week (7 days), do `c.add(Calendar.DATE, -7);`, for example. – Jesper Jun 11 '10 at 14:10
  • Thank You very much appreaciate your help . – user236501 Jun 11 '10 at 14:11
  • 15
    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 Jun 11 '10 at 14:53
  • 2
    However, your code simply _does not work reliably_. See my comment below and http://stackoverflow.com/questions/6722542 for an explanation. – Michael Piefel Sep 28 '11 at 14:15
  • jarnbjo, I love you! You solved my bug! I wanna buy you a beer. – 0xRLA Oct 02 '16 at 08:22
  • FYI, the troublesome old date-time classes such as `java.util.Date`, [`java.util.Calendar`](https://docs.oracle.com/javase/9/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/9/docs/api/java/time/package-summary.html) classes built into Java 8 & Java 9. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). See [Answer by Przemek](https://stackoverflow.com/a/33868624/642706). – Basil Bourque Dec 29 '17 at 07:34
12

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);
}
Gregor Koukkoullis
  • 2,255
  • 1
  • 21
  • 31
10

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
Przemek
  • 7,111
  • 3
  • 43
  • 52
9

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
  • 67,365
  • 22
  • 157
  • 181
6

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).

Michael Piefel
  • 18,660
  • 9
  • 81
  • 112
2

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
  • 18,126
  • 4
  • 62
  • 76
1

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

Sjoerd
  • 74,049
  • 16
  • 131
  • 175
1

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

kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
1
    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);

    }
Sibin
  • 511
  • 6
  • 10
0

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
  • 4,890
  • 1
  • 31
  • 42
  • theres another implementation @ http://helpdesk.objects.com.au/java/zellers-congruence-in-java". Though as mentioned in that post your better off using the Calendar class - http://helpdesk.objects.com.au/java/use-calendar-class-to-get-localized-day-names, which can also be used to get the first day of the week - http://helpdesk.objects.com.au/java/how-do-i-get-the-date-of-first-day-of-the-current-week – objects Nov 21 '10 at 01:30
-1

Yes. Use Joda Time

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

user334583
  • 55
  • 1