简体   繁体   中英

Get past weeks days date of current month

I try this but not get the format what i requires.

 SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd-MMM-yyyy");
    for (int i = 7; i >=1; i--) {
        Calendar calendar = new GregorianCalendar();
        calendar.add(Calendar.DATE, i);
        String day = sdf.format(calendar.getTime());
        Log.i("days", day);

Wednesday 06-Dec-2017 Tuesday 05-Dec-2017 Monday 04-Dec-2017 Sunday 03-Dec-2017 Saturday 02-Dec-2017 Friday 01-Dec-2017 Thursday 30-Nov-2017

I want format like this, Start date of week and End date of week..

Oct 1-7 Oct 8-14 Oct 15-21

Try this code,

 public static void getWeeksOfMonth(int month, int year)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd-MMM-yyyy");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, year);
        cal.set(Calendar.MONTH, month);
        cal.set(Calendar.DAY_OF_MONTH, 1);

        int ndays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
       System.out.println(ndays+"<<<ff" );

        for (int i = 1; i <= ndays; i++)
        {
            String day = sdf.format(cal.getTime());
            System.out.println(day+"<<<" );
              Log.e("", day+"<<<");
            if(i % 7 == 0){
                Log.e("", "=======week days===========");
            }
            cal.add(Calendar.DATE, 1);
        }

    }

// only previous week days get
  SimpleDateFormat sdf = new SimpleDateFormat("EEEE dd-MMM-yyyy");
        for (int i = 7; i >=1; i--) {
            Calendar calendar = new GregorianCalendar();
            calendar.add(Calendar.DATE, -i);
            String day = sdf.format(calendar.getTime());
            System.out.println(day+"<<<" );
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM