Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the start and the end date of a week using java calendar class

I want to get the last and the first week of a week for a given date. e.g if the date is 12th October 2011 then I need the dates 10th October 2011 (as the starting date of the week) and 16th october 2011 (as the end date of the week) Does anyone know how to get these 2 dates using the calender class (java.util.Calendar) thanks a lot!

like image 766
user421607 Avatar asked Oct 04 '11 08:10

user421607


People also ask

What is the first day of the week in Java?

By default, java. time uses the ISO 8601 standard. So Monday is the first day of the week (1) and Sunday is last (7).

What is calendar getInstance () in Java?

The getInstance() method in Calendar class is used to get a calendar using the current time zone and locale of the system. Syntax: public static Calendar getInstance() Parameters: The method does not take any parameters. Return Value: The method returns the calendar.


1 Answers

Some code how to do it with the Calendar object. I should also mention joda time library as it can help you many of Date/Calendar problems.

Code

public static void main(String[] args) {

    // set the date
    Calendar cal = Calendar.getInstance();
    cal.set(2011, 10 - 1, 12);

    // "calculate" the start date of the week
    Calendar first = (Calendar) cal.clone();
    first.add(Calendar.DAY_OF_WEEK, 
              first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));

    // and add six days to the end date
    Calendar last = (Calendar) first.clone();
    last.add(Calendar.DAY_OF_YEAR, 6);

    // print the result
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(df.format(first.getTime()) + " -> " + 
                       df.format(last.getTime()));
}
like image 80
dacwe Avatar answered Dec 25 '22 11:12

dacwe