Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dates of start and end of current week in Android

I need to find start and end day of current week in Android.

examples

today: Oct 12 2011 -> result: Oct 10 2011 - Oct 16 2011

today: Oct 1 2001 -> result: Sep 26 2011 - Oct 2 2011

today: Dec 30 2011 -> result: Dec 24 2001 - Jan 1 2011

Using c.get(Calendar.WEEK_OF_YEAR); I can get the week number but how to get the start & end date? I've found an answer here pointing to MonthDisplayHelper , but how to use it?

Thanks!

like image 244
SimoneB Avatar asked Nov 27 '22 07:11

SimoneB


2 Answers

Used this sintax and it worked

    Calendar c1 = Calendar.getInstance();

    //first day of week
    c1.set(Calendar.DAY_OF_WEEK, 1);

    int year1 = c1.get(Calendar.YEAR);
    int month1 = c1.get(Calendar.MONTH)+1;
    int day1 = c1.get(Calendar.DAY_OF_MONTH);

    //last day of week
    c1.set(Calendar.DAY_OF_WEEK, 7);

    int year7 = c1.get(Calendar.YEAR);
    int month7 = c1.get(Calendar.MONTH)+1;
    int day7 = c1.get(Calendar.DAY_OF_MONTH);  
like image 79
SimoneB Avatar answered Dec 10 '22 21:12

SimoneB


Here is the good example code, which gives you the current week of the year as well as week starting and ending date, Just what you need to do is set the starting day of the week in code, In my case I set it as SUNDAY,

// get Current Week of the year
    calendar=Calendar.getInstance();
    Log.v("Current Week", String.valueOf(calendar.get(Calendar.WEEK_OF_YEAR)));
    int current_week=calendar.get(Calendar.WEEK_OF_YEAR);
    int week_start_day=calendar.getFirstDayOfWeek(); // this will get the starting day os week in integer format i-e 1 if monday
    Toast.makeText(getContext(),"Current Week is"+current_week +"Start Day is"+week_start_day,Toast.LENGTH_SHORT).show();


    // get the starting and ending date
    // Set the calendar to sunday of the current week
    calendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
    System.out.println("Current week = " + Calendar.DAY_OF_WEEK);

    // Print dates of the current week starting on Sunday
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    String startDate = "", endDate = "";

    startDate = df.format(calendar.getTime());
    calendar.add(Calendar.DATE, 6);
    endDate = df.format(calendar.getTime());

    System.out.println("Start Date = " + startDate);
    System.out.println("End Date = " + endDate);
like image 20
Tara Avatar answered Dec 10 '22 22:12

Tara