4

I build a web-application with servlet and JSPs and inside my Servlet I compute the number of the week:

 private int findWeekNumber(String myDate) 
    throws ParseException{
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date date;
        date = df.parse(myDate);
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int week = cal.get(Calendar.WEEK_OF_YEAR);
        System.out.println("week number is:" + week);

        return week;
    }

and then I save the week to my Database. Then I retrieve the week from my Database. How can I get the start - end dates of the week (Week start is Monday) from the week? Lets say the weekNumber is 30 and I want to compute the 20/07/2015 - 26/07/2015. The same function is here

VedantK
  • 9,728
  • 7
  • 66
  • 71
yaylitzis
  • 5,354
  • 17
  • 62
  • 107

4 Answers4

10

The Java 8 version

LocalDate week = LocalDate.now().with(ChronoField.ALIGNED_WEEK_OF_YEAR, yourWeekNumber);

LocalDate start = week.with(DayOfWeek.MONDAY);
LocalDate end = start.plusDays(6);
System.out.println(start +" - "+ end);
PDStat
  • 5,513
  • 10
  • 51
  • 86
  • 2
    Two things: `LocalDate#with` is no static method, you need a LocalDate object (e.g. `LocalDate.of(2015, 1, 1)`) to call the method. And the correct end date is `start.plusDays(6)`, not `week.plusDays(6)`. – Modus Tollens Jul 24 '15 at 11:02
  • Thanks, answer adjusted – PDStat Jul 24 '15 at 11:27
  • You need to specify a time zone. If omitted, the JVM's current default time zone is applied. Time zone is crucial in deterring the date. A new day dawns earlier in Paris, for example, than Montréal. – Basil Bourque Jul 24 '15 at 16:30
  • Is there no better solution? Throwing away a `LocalDate` instance doesn't look right to me. – xehpuk Jan 06 '16 at 17:48
2

java.time

The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.

Also, quoted below is a notice from the home page of Joda-Time:

Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project.

Solution using java.time, the modern Date-Time API:

import java.time.LocalDate;
import java.time.Year;
import java.time.temporal.WeekFields;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Test
        int weekNumber = 34;
        System.out.printf("%s - %s%n", getFirstDayOfWeek(weekNumber, Locale.UK),
                getLastDayOfWeek(weekNumber, Locale.UK));
        System.out.printf("%s - %s%n", getFirstDayOfWeek(weekNumber, Locale.US),
                getLastDayOfWeek(weekNumber, Locale.US));
    }

    static LocalDate getFirstDayOfWeek(int weekNumber, Locale locale) {
        return LocalDate
                .of(Year.now().getValue(), 2, 1)
                .with(WeekFields.of(locale).getFirstDayOfWeek())
                .with(WeekFields.of(locale).weekOfWeekBasedYear(), weekNumber);
    }

    static LocalDate getLastDayOfWeek(int weekNumber, Locale locale) {
        return getFirstDayOfWeek(weekNumber, locale).plusDays(6);
    }
}

Output:

2021-08-23 - 2021-08-29
2021-08-15 - 2021-08-21

ONLINE DEMO

Note that the first day of the week is Locale-dependent e.g. it is Monday in the UK while Sunday in the US. As per the ISO 8601 standards, it is Monday. For comparison, check the US calendar and the UK calendar.

Learn more about the modern Date-Time API from Trail: Date Time.


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
1

From week number:

Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
int year = cal.get(Calendar.YEAR);

Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, year);


calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.DAY_OF_WEEK, 1);
   // Now get the first day of week.
Date sDate = calendar.getTime();
System.out.println(sDate);

calendar.set(Calendar.WEEK_OF_YEAR, (week));
calendar.set(Calendar.DAY_OF_WEEK, 7);
Date eDate = calendar.getTime();
System.out.println(eDate);

Another Solution

Iff - without week number

Date date = new Date();
Calendar c = Calendar.getInstance();
c.setTime(date);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK) - c.getFirstDayOfWeek();
c.add(Calendar.DAY_OF_MONTH, -dayOfWeek);

Date weekStart = c.getTime();
// we do not need the same day a week after, that's why use 6, not 7
c.add(Calendar.DAY_OF_MONTH, 6); 
Date weekEnd = c.getTime();

System.out.println(weekStart);
System.out.println(weekEnd);
Sarz
  • 1,970
  • 4
  • 23
  • 43
  • You don't use week number to calculate the weekstart, weekEnd. The int variable `week` is my clue to compute the start/end dates. – yaylitzis Jul 24 '15 at 09:38
1

You can use Calendar for this,

 Calendar cal = Calendar.getInstance();
 cal.set(Calendar.WEEK_OF_YEAR, week);
 Date yourDate = cal.getTime();

 cal.setTime(yourDate);//Set specific Date of which start and end you want

 Date start,end;

 cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
 start = cal.getTime();//Date of Monday of current week

 cal.add(Calendar.DATE, 6);//Add 6 days to get Sunday of next week
 cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
 end = cal.getTime();//Date of Sunday of current week
 System.out.println(start +" - "+ end);
akash
  • 22,664
  • 11
  • 59
  • 87
  • But you don't use week number to calculate the weekstart, weekEnd. The int variable `week` is my clue to compute the start/end dates – yaylitzis Jul 24 '15 at 09:52
  • @Nat95 But you can use `date` as well. :) and `week` will give you at which position out of 52 your week stands. – akash Jul 24 '15 at 09:53
  • Weeks don't always start on a Monday and end on a Sunday. – biziclop Jul 24 '15 at 09:59
  • @TAsk forgive my but I don't understand how I will use the clue that I have, which is `int` var `week` (e.g. 30) in your code – yaylitzis Jul 24 '15 at 10:28
  • I am saying that, because I save to my DB the `week`. When I retrieve it, i want then to calculate the start-end week dates. – yaylitzis Jul 24 '15 at 10:29
  • @TAsk I get an exception `Exceptionn: java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date` – yaylitzis Jul 24 '15 at 10:44