java 我想获得特定月份的周数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14454736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:19:41  来源:igfitidea点击:

I want to get number of weeks in a particular month

javaandroidcalendar

提问by Nezam

i want to get number of weeks in current month.That including the previous month's days in the last week and the first week days in the next month.

我想获得当月的周数。这包括上周的上个月和下个月的第一个工作日。

Something like this:

像这样的东西:

Simple Isnt it?

简单不是吗?

I want to use this in a certain gridview adapter on android and am trying to manipulate this code block:

我想在 android 上的某个 gridview 适配器中使用它,并尝试操作此代码块:

            //FIRST_DAY_OF_WEEK =0;
    int lastDay = month.getActualMaximum(Calendar.DAY_OF_MONTH);
    int firstDay = (int) month.get(Calendar.DAY_OF_WEEK);
    int firstDayNextMonth = nextMonth.get(Calendar.DAY_OF_WEEK);
    int lastDayNextMonth=nextMonth.getActualMaximum(Calendar.DAY_OF_MONTH);
    int nextMonthdays=nextMonth.getMinimalDaysInFirstWeek();

    // figure size of the array
    if (firstDay == 1) {
        days = new String[lastDay + (FIRST_DAY_OF_WEEK * 6)];
    }

    else {
        days = new String[lastDay + firstDay - (FIRST_DAY_OF_WEEK + 1)];
    }

采纳答案by VendettaDroid

The WEEK_OF_YEAR attribute of the Calendar class can be useful for you. Ref: Calendar class

Calendar 类的 WEEK_OF_YEAR 属性对您很有用。参考:日历类

Create a new date that will be the first day of the some month. Get the week of the year for this day, let say you got start value.

创建一个新日期,该日期将是某个月的第一天。获取这一天的一年中的一周,假设您获得了起始值。

Create a new date that will be the last day of the given month. Get the week of the year for this day, so now you got end value.

创建一个新日期,作为给定月份的最后一天。获取这一天的一年中的第几周,因此现在您获得了最终值。

Now end - start + 1 should be one that you want.

现在结束 - 开始 + 1 应该是你想要的。

You may have to handle some corner case when the week overlaps to another year or similar. But I think once you get this right, you can do that with simple logic.

当一周与另一年或类似的时间重叠时,您可能需要处理一些极端情况。但我认为一旦你做对了,你就可以用简单的逻辑来做到这一点。

Here is simple example code. I think you can make it into function and pass whatever you want.

这是简单的示例代码。我认为你可以让它发挥作用并通过你想要的任何东西。

        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, 2013);
        cal.set(Calendar.MONTH, 1);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        int start = cal.get(Calendar.WEEK_OF_YEAR);
        Log.d("BLA BLA", "Value is " + start);
        cal.set(Calendar.YEAR, 2013);
        cal.set(Calendar.MONTH, 1);
        cal.set(Calendar.DAY_OF_MONTH, 28);
        int end = cal.get(Calendar.WEEK_OF_YEAR);
        //Above line will not work for December Month, use following line for this
        int end = isDecember?53:cal.get(Calendar.WEEK_OF_YEAR);
        Log.d("BLA BLA", "Value is " + end);
        Log.d("BLA BLA", "Num weeks:: " + (end - start +1 ));

For Corner case:

对于角落案例:

Corner case will only occur for the month of Januaray (E.g Jan 2010, Jan 2000) in those cases most of the days are part of the last week of the previous year so the start value will be 52 and end value will be 5. When this occurs check if,

角情况只会发生在 Januaray 月份(例如 2010 年 1 月,2000 年 1 月),在这些情况下,大多数日子是前一年最后一周的一部分,因此开始值为 52,结束值为 5。当发生这种情况检查,

          if(start > end) {
                numweeks = end + 1;
             }

P.S: Put it to different testing inputs that you got. Let me know If I can improve on it once you find any fault.

PS:把它放在你得到的不同测试输入上。如果您发现任何错误,请告诉我是否可以改进。

And Even much simpler solution:

甚至更简单的解决方案:

        Calendar cal = Calendar.getInstance();
        for(int i = 0 ; i < 11;i++){
            cal.set(Calendar.YEAR, 2013);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            cal.set(Calendar.MONTH, i);
            int maxWeeknumber = cal.getActualMaximum(Calendar.WEEK_OF_MONTH);
            Log.d("LOG","max week number" + maxWeeknumber);
        }

        01-22 01:49:03.591: D/LOG(573): max week number5
        01-22 01:49:03.602: D/LOG(573): max week number5
        01-22 01:49:03.602: D/LOG(573): max week number6
        01-22 01:49:03.671: D/LOG(573): max week number5
        01-22 01:49:03.671: D/LOG(573): max week number5
        01-22 01:49:03.671: D/LOG(573): max week number6
        01-22 01:49:03.681: D/LOG(573): max week number5
        01-22 01:49:03.691: D/LOG(573): max week number5
        01-22 01:49:03.691: D/LOG(573): max week number5
        01-22 01:49:03.711: D/LOG(573): max week number5
        01-22 01:49:03.711: D/LOG(573): max week number5

Simple solution works fine with corner cases:

简单的解决方案适用于极端情况:

        Calendar cal = Calendar.getInstance();
        for(int i = 0 ; i < 11;i++){
            cal.set(Calendar.YEAR, 2010);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            cal.set(Calendar.MONTH, i);
            int maxWeeknumber = cal.getActualMaximum(Calendar.WEEK_OF_MONTH);
            // Month value starts from 0 to 11 for Jan to Dec
            Log.d("LOG","For Month :: "+ i + " Num Week :: " + maxWeeknumber);
        }

Log:

日志:

        01-22 01:59:35.841: D/LOG(629): For Month :: 0 Num Week :: 6
        01-22 01:59:35.841: D/LOG(629): For Month :: 1 Num Week :: 5
        01-22 01:59:35.841: D/LOG(629): For Month :: 2 Num Week :: 5
        01-22 01:59:35.841: D/LOG(629): For Month :: 3 Num Week :: 5
        01-22 01:59:35.841: D/LOG(629): For Month :: 4 Num Week :: 6
        01-22 01:59:35.852: D/LOG(629): For Month :: 5 Num Week :: 5
        01-22 01:59:35.871: D/LOG(629): For Month :: 6 Num Week :: 5
        01-22 01:59:35.871: D/LOG(629): For Month :: 7 Num Week :: 5
        01-22 01:59:35.871: D/LOG(629): For Month :: 8 Num Week :: 5
        01-22 01:59:35.871: D/LOG(629): For Month :: 9 Num Week :: 6
        01-22 01:59:35.871: D/LOG(629): For Month :: 10 Num Week :: 5

回答by zzzhc

use WEEK_OF_MONTH will be better, no cross year issue.

使用 WEEK_OF_MONTH 会更好,没有跨年问题。

public static void main(String[] args) throws Exception {
  for (String m : new String[] { "2012-11", "2012-12", "2013-01", "2013-02", "2013-03",
              "2013-04", "2013-05", "2013-06" }) {
      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
      Date date = format.parse(m);
      Calendar c = Calendar.getInstance();
      c.setTime(date);

      int start = c.get(Calendar.WEEK_OF_MONTH);

      c.add(Calendar.MONTH, 1);
      c.add(Calendar.DATE, -1);
      int end = c.get(Calendar.WEEK_OF_MONTH);
      System.out.println(" # of weeks in " + format.format(c.getTime())
              + ": " + (end - start + 1));
  }
}

results:

结果:

# of weeks in 2012-11: 5
# of weeks in 2012-12: 6
# of weeks in 2013-01: 5
# of weeks in 2013-02: 5
# of weeks in 2013-03: 6
# of weeks in 2013-04: 5
# of weeks in 2013-05: 5
# of weeks in 2013-06: 6

回答by Vardaan Sharma

We can use the calendar class and then do something like

我们可以使用日历类,然后做类似的事情

Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getActualMaximum(Calendar.WEEK_OF_MONTH));

this will return the number of weeks in the current month

这将返回当月的周数

回答by AlexanderChatterjee

if you want to do it by "hand"

如果你想用“手”来做

use this:

用这个:

Date.prototype.getMonthWeek = function(monthAdjustement)
{    

    var firstDay = new Date(this.getFullYear(), this.getMonth(), 1).getDay();

    var returnMessage = (Math.ceil(this.getDate()/7) + Math.floor(((7-firstDay)/7)));

    return returnMessage;

}

Where monthAdjustementis just an Integer adjusting the month you seek compared to Today's date.

monthAdjustement与今天的日期相比,哪里只是调整您要查找的月份的整数。

回答by Swapnil

Let's assume we know the first day of the month (Saturday, Sunday etc).

假设我们知道一个月的第一天(周六、周日等)。

  • If 1st day of the month is a Sundayand it's not a leap-year, then the (correction edit) Februarymonth will have only 4 weeks. Otherwise, in all the cases, it should have at least 5 and at most 6 weeks.
  • Now, if your month starts on Saturday, you'll always have 6 weeks (excluding if it is February, when it there will be 5)
  • Now, if your month starts on Friday, you'll have 6 weeks for months having 31 days and 5 for all others.
  • For rest of the cases, it will always be 5 weeks.
  • 如果一个月的第一天是 aSunday并且它不是闰年,那么(更正编辑)February月份将只有 4 周。否则,在所有情况下,它应该至少有 5 周,最多 6 周。
  • 现在,如果您的月份从 开始Saturday,您将始终有 6 周(不包括如果是 2 月,那么将会有 5 周)
  • 现在,如果您的月份从 开始Friday,那么您将有 6 周的月份,其中有 31 天,其他月份为 5 天。
  • 对于其余情况,将始终为 5 周。

Finding out the 1st day of the month shouldn't be difficult, you can use Calendaror other date/time utility library classes. However, I guess there could be cleaner solutions removing the corner cases and unnecessary complexity.

找出一个月的第一天应该不难,您可以使用Calendar或其他日期/时间实用程序库类。但是,我想可能会有更干净的解决方案,消除极端情况和不必要的复杂性。