如何根据Java中的日历周从日历年中明智地获取数据

时间:2019-01-25 12:32:18

标签: java

我无法根据日历周从日历年每周动态地分离数据。 enter image description here

假设我的日历月为2019年1月,我想每周进行一次数据分离,那么本月我们有5周的时间

1st week from 1-jan to 6-jan
2nd week from 7-jan to 13-jan
3rd week from  14-jan to 20-jan
4th week from 21-jan to 27-jan and 
5th week from 28-jan to 31 Jan and so on...

任何人都可以建议任何人我该怎么做。

1 个答案:

答案 0 :(得分:0)

那呢:

    //create calendar with locale
    Calendar cal = Calendar.getInstance(Locale.GERMANY);

    //week of year you want
    int weekOfYear = 4;

    //set calendar to specified week of year
    cal.set(Calendar.WEEK_OF_YEAR, weekOfYear);

    //set calendar to first day of the week
    //(might be different in different locales)
    cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());

    //print dates of this week
    DateFormat df = new SimpleDateFormat("EEE yyyy/MM/dd");
    for (int i = 0; i < 7; i++) {
        System.out.println(df.format(cal.getTime()));
        cal.add(Calendar.DATE, 1);
    }

它设置为一年的第4周(通过将weekOfYear设置为4)并打印以下内容:

Mon 2019/01/21
Tue 2019/01/22
Wed 2019/01/23
Thu 2019/01/24
Fri 2019/01/25
Sat 2019/01/26
Sun 2019/01/27

是您需要的吗?

编辑:或者甚至(更接近您的要求):

    //create calendar with locale
    Calendar cal = Calendar.getInstance(Locale.GERMANY);

    //weeks of year you want
    int fromWeek = 1;
    int toWeek = 10;

    //date format
    DateFormat df = new SimpleDateFormat("EEE yyyy/MM/dd");

    //print date range
    for (int i = fromWeek; i <= toWeek; i++) {
        //set calendar to specified week of year
        cal.set(Calendar.WEEK_OF_YEAR, i);
        //set calendar to first day of the week
        //(might be different in different locales)
        cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());

        //print date range of this week
        System.out.print(
            "Week no. " + i + " from " +
            df.format(cal.getTime()) + " to "
        );
        cal.add(Calendar.DAY_OF_YEAR, 6);
        System.out.println(df.format(cal.getTime()));
    }

它打印:

Week no. 1 from Mon 2018/12/31 to Sun 2019/01/06
Week no. 2 from Mon 2019/01/07 to Sun 2019/01/13
Week no. 3 from Mon 2019/01/14 to Sun 2019/01/20
Week no. 4 from Mon 2019/01/21 to Sun 2019/01/27
Week no. 5 from Mon 2019/01/28 to Sun 2019/02/03
Week no. 6 from Mon 2019/02/04 to Sun 2019/02/10
Week no. 7 from Mon 2019/02/11 to Sun 2019/02/17
Week no. 8 from Mon 2019/02/18 to Sun 2019/02/24
Week no. 9 from Mon 2019/02/25 to Sun 2019/03/03
Week no. 10 from Mon 2019/03/04 to Sun 2019/03/10