get week start and end date from week number & year in android

10,328

Solution 1

You can use the following method to get first date and end date of a week

 void getStartEndOFWeek(int enterWeek, int enterYear){
//enterWeek is week number
//enterYear is year
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.WEEK_OF_YEAR, enterWeek);
        calendar.set(Calendar.YEAR, enterYear);

        SimpleDateFormat formatter = new SimpleDateFormat("ddMMM yyyy"); // PST`
        Date startDate = calendar.getTime();
        String startDateInStr = formatter.format(startDate);
        System.out.println("...date..."+startDateInStr);

        calendar.add(Calendar.DATE, 6);
        Date enddate = calendar.getTime();
        String endDaString = formatter.format(enddate);
        System.out.println("...date..."+endDaString);
    }

Solution 2

You need to use the java.util.Calendar class. You can set the year with Calendar.YEAR and the week of year with Calendar.WEEK_OF_YEAR using the public void set(int field, int value) method.

As long as the locale is set properly, you can even use setFirstDayOfWeek to change the first day of the week. The date represented by your calendar instance will be your start date. Simply add 6 days for your end date.

Calendar calendar = new GregorianCalendar();
// Clear the calendar since the default is the current time
calendar.clear(); 
// Directly set year and week of year
calendar.set(Calendar.YEAR, 2011);
calendar.set(Calendar.WEEK_OF_YEAR, 51);
// Start date for the week
Date startDate = calendar.getTime();
// Add 6 days to reach the last day of the current week
calendar.add(Calendar.DAY_OF_YEAR, 6);
// End date for the week
Date endDate = calendar.getTime();
Share:
10,328
AndroidGuy
Author by

AndroidGuy

SOreadytohelp Android Software Developer

Updated on June 11, 2022

Comments

  • AndroidGuy
    AndroidGuy about 2 years

    I wish to get the start date & end date of the week, for a week number passed in to the method. For example, if i pass the week number as 51 and the year as 2011, it should return me start date as 18 Dec 2011 and the end date as 24 Dec 2011

    Are there any methods that will help me achieve this?

  • kamal_tech_view
    kamal_tech_view over 11 years
    year of 2015, 2016 come one week more but 2013,2014 come exactly... is this the issue of leap year..
  • Deva
    Deva over 8 years
    Hi Kamal, any solution for above mentioned issue??