0

My requirement is to get the start and end date of the week when date is passed. I have searched and i found tons of answers but confused with which one is best to use.In one of the thread i found the below code:

  Calendar c = Calendar.getInstance();
    c.setTime(new Date("8/16/2017"));
    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
    System.out.println("day :" + dayOfWeek);
    c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
    System.out.println("start of week day :" + c.getTime());

output:

day :4
start of week day :Sun Aug 13 00:00:00 EDT 2017

I see a bug in the above code output. Start of the week should be Monday Aug14 but it shows Sun Aug13. Any suggestions to get the start date and end date of the week when date is passed as a String dynamically.

--EDITED-- I'm looking for java code which returns the first and last day date's of the week when date is passed.

scrit
  • 241
  • 1
  • 5
  • 12
  • 3
    Sunday is the first day of the calendar week. – drelliot Aug 16 '17 at 18:08
  • https://stackoverflow.com/questions/11858565/how-to-set-first-day-of-week-in-a-java-application-calendar – Jacek Cz Aug 16 '17 at 18:09
  • I'm looking for both first day and last day dates of the week when date is passed. – scrit Aug 16 '17 at 18:10
  • It's Java being diabolically idiosyncratic and against ISO. It gets worse: January is also the zeroth month of the year! The new time class sorts out this mess. – Bathsheba Aug 16 '17 at 18:11
  • Any Answer using `Calendar` or `Date` is certainly not the way to go. Those troublesome classes are now supplanted by the java.time classes. – Basil Bourque Aug 16 '17 at 23:50

2 Answers2

8
import java.time.LocalDate;

import static java.time.DayOfWeek.MONDAY;
import static java.time.DayOfWeek.SUNDAY;
import static java.time.temporal.TemporalAdjusters.nextOrSame;
import static java.time.temporal.TemporalAdjusters.previousOrSame;

public class FirstAndLast
{
  public static void main(String[] args)
  {
    LocalDate today = LocalDate.now();

    LocalDate monday = today.with(previousOrSame(MONDAY));
    LocalDate sunday = today.with(nextOrSame(SUNDAY));

    System.out.println("Today: " + today);
    System.out.println("Monday of the Week: " + monday);
    System.out.println("Sunday of the Week: " + sunday);
  }
}
Akash
  • 587
  • 5
  • 12
2
    Calendar c = Calendar.getInstance();
    c.setFirstDayOfWeek(Calendar.MONDAY); //Line2
    c.setTime(new Date("8/16/2017"));
    int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
    System.out.println("day :" + dayOfWeek);
    c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
    System.out.println("start of week day :" + c.getTime());

Set the first day of the week to Monday as in line 2.

Now the output will be

 day :4
 start of week day :Mon Aug 14 00:00:00 EDT 2017