简体   繁体   中英

What is the difference between Calendar.WEEK_OF_MONTH and Calendar.DAY_OF_WEEK_IN_MONTH in Java's Calendar class?

Java's Calendar class provides for two fields: WEEK_OF_MONTH and DAY_OF_WEEK_IN_MONTH. Can someone explain the difference to me? It seems that they both return the same value when tested using the code below:

Calendar date = Calendar.getInstance();
date.set(2011,5,29);
int weekNo1 = date.get(Calendar.WEEK_OF_MONTH);
int weekNo2 = date.get(Calendar.DAY_OF_WEEK_IN_MONTH);

The difference is that DAY_OF_WEEK_IN_MONTH provides the number of times the weekday has occurred during the month and WEEK_OF_MONTH just returns the week number within the current month. Think of it this way, if the month starts on a Wednesday, the first Monday will occur during the second week of the month. The value for DAY_OF_WEEK_IN_MONTH for that Monday would be 1, but the WEEK_OF_MONTH would be 2.

  • Calendar.WEEK_OF_MONTH simply returns "Current week number in current month"
  • Calendar.DAY_OF_WEEK simply returns "Current day number in current week starting on last Sunday"
  • Calendar.DAY_OF_WEEK_IN_MONTH returns "N if current day is Nth day of month" say "3 if today is 3rd Wednesday in month"

So I am writing this on 21st December 2016:

在此输入图像描述

And this is what I am getting:

Calendar today = Calendar.getInstance();
System.out.println(today.get(Calendar.DAY_OF_WEEK));          //outputs 4, as today is 4th day in this week which started on 18
System.out.println(today.get(Calendar.DAY_OF_WEEK_IN_MONTH)); //outputs 3, as today is "3rd Wednesday of this month". Earlier two wednesday were on 7th and 14th
System.out.println(today.get(Calendar.WEEK_OF_MONTH));        //outputs 4, as currently 4th week of a month is running

I found all of the other docs confusing, so for any Microsoft developers like myself this one might be clear for you, as it was for me:

http://msdn.microsoft.com/en-us/library/aa986432(v=vs.80).aspx

A constant representing a value for how many times a given day has occurred in the month.

Week of Month is the week within the current month starting from sundays how many weeks have there been.

Day of week of month is the day 5 would be Thursday, 1 sunday ect.

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