1

I have week number and year, and I would like to get the date of the first day of week and the last one, this is my code, it gives me wrong result, please tell me what I'm I doing wrong. thanks in advance.

SimpleDateFormat dt = new SimpleDateFormat("dd/mm/yyyy"); 
String start ="";
String end ="";
int week = 38;
int yeat = 2016;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.YEAR, year); 
// firt day of week
start = dt.format(calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, 6);
//last day of week
end = dt.format(calendar.getTime());
Morteza Asadi
  • 1,819
  • 2
  • 22
  • 39
Sfayn
  • 190
  • 1
  • 2
  • 13
  • Possible duplicate: [How to calculate Date from ISO8601 week number in Java](http://stackoverflow.com/q/25084576/642706) – Basil Bourque Dec 28 '16 at 23:08

3 Answers3

2

If you use Java 8+, you could use the built-in week-date formatter:

int week = 38;
int year = 2016;
String weekYear = year + "-W" + week + "-7"; //2016-W38-7
LocalDate d = LocalDate.parse(year + "-W" + week + "-7", ISO_WEEK_DATE); //2016-09-25

Note: the -7 at the end of the string represents the last day of the week (i.e. sunday).

assylias
  • 321,522
  • 82
  • 660
  • 783
2
  • Correct the DateFormatter syntax, month should be in capital case
  • Get the date for Sunday and Saturday in that particular week for the year passed.

      SimpleDateFormat dt = new SimpleDateFormat("dd/MM/yyyy"); 
         String start ="";
         String end ="";
         int week = 38;
         int year = 2016;
         Calendar calendar = Calendar.getInstance();
         calendar.set(Calendar.YEAR, year); 
         calendar.set(Calendar.DAY_OF_WEEK,Calendar.SUNDAY);
         calendar.set(Calendar.WEEK_OF_YEAR, week);
          start = dt.format(calendar.getTime());
         calendar.set(Calendar.DAY_OF_WEEK,Calendar.SATURDAY);
           end = dt.format(calendar.getTime());
         System.out.println(start+" |"+end);
    
Amit Bhati
  • 5,569
  • 1
  • 24
  • 45
0

Try this:

SimpleDateFormat dt = new SimpleDateFormat("dd/mm/yyyy"); 
String start ="";
String end ="";
int week = 38;
int year = 2016;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.YEAR, year); 

// firt day of week
Calendar cal = calendar;
while (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) {
    cal.add(Calendar.DATE, -1);
}
start = dt.format(cal.getTime());
System.out.println(start);

Calendar cal1 = calendar;
while (cal1.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) {
    cal1.add(Calendar.DATE, 1);
}
//last day of week
end = dt.format(cal1.getTime());
System.out.println(end);
SujitKumar
  • 142
  • 1
  • 10