Lalit Sharma
Lalit Sharma

Reputation: 1150

How to get First Day and last day of the week of a date

I am using DatePickerDialog to show the calender. I want to access First day and last day of the week of the date selected.

Here is what I have tried

     this.tv_date.setText( new StringBuilder()
        // Month is 0 based so add 1
                    .append(mDay).append("-")
                    .append(monthName).append("-")
                    .append(mYear).append(""));
        tv_date.setHighlightColor(Color.CYAN);

        String str=mDay+"-"+mMonth+"-"+mYear;

        SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
        sdf.format(""+str); //here I am getting exception

        Calendar cal=Calendar.getInstance();

        int s=  cal.getFirstDayOfWeek();

        Toast.makeText(getApplicationContext(), "first day of the week : "+s, 1).show();

But I am getting "IllegalArguementException". Please help me

Thanks

Upvotes: 0

Views: 4339

Answers (2)

Rahul
Rahul

Reputation: 45060

sdf.format(""+str); - is wrong. You either need to pass a Date object to it, or else, change it to sdf.parse(str); to get a Date object from it.

Edit:- To get the first day of the week, do this.

String str=mDay+"-"+mMonth+"-"+mYear;
SimpleDateFormat sdf=new SimpleDateFormat("dd-MM-yyyy");
Date myDate = new Date();
try{
    myDate = sdf.parse(str);
}catch(ParseException pe){
    // Do Something
}
Calendar cal = Calendar.getInstance();  
cal.setTime(myDate);
cal.set(Calendar.DAY_OF_WEEK, 1);  
int s = cal.get(Calendar.DATE);

Upvotes: 4

Linga
Linga

Reputation: 10555

Here is an example of calculating the first day of week.

private void firstDayOfThisWeek(){
 DateTime today = DateTime.today(TimeZone.getDefault()); 
 DateTime firstDayThisWeek = today; //start value 
 int todaysWeekday = today.getWeekDay();
 int SUNDAY = 1;
 if(todaysWeekday > SUNDAY){
   int numDaysFromSunday = todaysWeekday - SUNDAY;
   firstDayThisWeek = today.minusDays(numDaysFromSunday);
 }
 System.out.println("The first day of this week is : " + firstDayThisWeek);
}

Instead of assigning today you can assign any other day with exact format

Upvotes: 0

Related Questions