在Java中获得上个星期五的月份

时间:2022-04-26 09:17:46

I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Java, but I was wondering if anyone knew of anything more concise or efficient. Below is what I tested with for this year:

我正在开发一个项目,其中要求将日期计算为给定月份的最后一个星期五。我想我有一个只使用标准Java的解决方案,但我想知道是否有人知道更简洁或更有效的东西。以下是我今年测试的内容:

    for (int month = 0; month < 13; month++) {
        GregorianCalendar d = new GregorianCalendar();
        d.set(d.MONTH, month);
        System.out.println("Last Week of Month in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + d.getLeastMaximum(d.WEEK_OF_MONTH));
        d.set(d.DAY_OF_WEEK, d.FRIDAY);
        d.set(d.WEEK_OF_MONTH, d.getActualMaximum(d.WEEK_OF_MONTH));
        while (d.get(d.MONTH) > month || d.get(d.MONTH) < month) {
            d.add(d.WEEK_OF_MONTH, -1);
        }
        Date dt = d.getTime();
        System.out.println("Last Friday of Last Week in  " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + dt.toString());
    }

17 个解决方案

#1


24  

Based on marked23's suggestion:

基于标记23的建议:

public Date getLastFriday( int month, int year ) {
   Calendar cal = Calendar.getInstance();
   cal.set( year, month + 1, 1 );
   cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) );
   return cal.getTime();
}

#2


34  

Let Calendar.class do its magic for you ;)

让Calendar.class为你做神奇的事;)

pCal.set(GregorianCalendar.DAY_OF_WEEK,Calendar.FRIDAY);
pCal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);

#3


9  

You never need to loop to find this out. For determining the "last Friday" date for this month, start with the first day of next month. Subtract the appropriate number of days depending on what (numerical) day of the week the first day of the month falls on. There's your "last Friday." I'm pretty sure it can be boiled down to a longish one-liner, but I'm not a java dev. So I'll leave that to someone else.

你永远不需要循环来找到它。要确定本月的“上周五”日期,请从下个月的第一天开始。减去适当的天数,具体取决于每月第一天的某一天(数字)日期。这是你的“上周五”。我很确定它可以归结为一个冗长的单行程序,但我不是一个java开发人员。所以我会把它留给别人。

#4


8  

java.time

Using java.time library built into Java 8 and later, you may use TemporalAdjusters.lastInMonth:

使用Java 8及更高版本中内置的java.time库,您可以使用TemporalAdjusters.lastInMonth:

val now = LocalDate.now() 
val lastInMonth = now.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY))

You may choose any day from the DayOfWeek enum.

您可以从DayOfWeek枚举中选择任何一天。

If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like

如果您需要添加时间信息,可以使用任何可用的LocalDate到LocalDateTime转换

lastFriday.atStartOfDay() // e.g. 2015-11-27T00:00

#5


7  

I would use a library like Jodatime. It has a very useful API and it uses normal month numbers. And best of all, it is thread safe.

我会使用像Jodatime这样的库。它有一个非常有用的API,它使用正常的月号。最重要的是,它是线程安全的。

I think that you can have a solution with (but possibly not the shortest, but certainly more readable):

我认为你可以有一个解决方案(但可能不是最短的,但肯定更具可读性):

DateTime now = new DateTime();      
DateTime dt = now.dayOfMonth().withMaximumValue().withDayOfWeek(DateTimeConstants.FRIDAY);
if (dt.getMonthOfYear() != now.getMonthOfYear()) {
  dt = dt.minusDays(7);
}       
System.out.println(dt);

#6


2  

You need to know two things - the number of days in the month, and the weekday the first of the month falls on.

您需要知道两件事 - 本月的天数和本月的第一天的工作日。

If the first day of the month is a

如果该月的第一天是

  • Sunday, then the last Friday is always the 27th.
  • 星期天,那么最后一个星期五总是27日。

  • Monday, then the last Friday is always the 26th.
  • 星期一,那么最后一个星期五总是26日。

  • Tuesday, then the last Friday is always the 25th.
  • 星期二,那么上周五总是25日。

  • Wednesday, then the last Friday is the 24th, unless there are 31 days in the month, then it's the 31st
  • 星期三,那么最后一个星期五是24日,除非这个月有31天,那么它是第31天

  • Thursday, then the last Friday is the 23rd, unless there are 30 days or more in the month, then it's the 30th.
  • 星期四,那么最后一个星期五是23日,除非这个月有30天或更长时间,那么它是30日。

  • Friday, then the last Friday is the 22nd, unless there are 29 days or more in the month, then it's the 29th.
  • 星期五,那么最后一个星期五是22日,除非本月有29天或更长时间,那么它是第29天。

  • Saturday, then the last Friday is always the 28th.
  • 星期六,那么上周五总是28日。

There are only three special cases. A single switch statement and three if statements (or ternary operators if you like every case to have a single line...)

只有三个特例。一个switch语句和三个if语句(如果你喜欢每个case都有一行三元运算符......)

Work it out on paper. Don't need any special libraries, functions, julian conversions, etc (well, except to get the weekday the 1st falls on, and maybe the number of days that month... )

在纸上解决。不需要任何特殊的库,函数,朱利安转换等(好吧,除了让第一个工作日到来,也许那个月的天数......)

Aaron implemented it in Java.

Aaron用Java实现了它。

-Adam

#7


2  

code for Adam Davis's algorithm

Adam Davis算法的代码

public static int getLastFriday(int month, int year)
{
Calendar cal = Calendar.getInstance();
cal.set(year, month, 1, 0, 0, 0); // set to first day of the month
cal.set(Calendar.MILLISECOND, 0);

int firstDay = cal.get(Calendar.DAY_OF_WEEK);
int daysOfMonth = cal.getMaximum(Calendar.DAY_OF_MONTH);

switch (firstDay)
{
    case Calendar.SUNDAY :
        return 27;
    case Calendar.MONDAY :
        return 26;
    case Calendar.TUESDAY :
        return 25;
    case Calendar.WEDNESDAY :
        if (daysOfMonth == 31) return 31;
        return 24;
    case Calendar.THURSDAY :
        if (daysOfMonth >= 30) return 30;
        return 23;
    case Calendar.FRIDAY :
        if (daysOfMonth >= 29) return 29;
        return 22;
    case Calendar.SATURDAY :
        return 28;
}
throw new RuntimeException("what day of the month?");
}}

#8


1  

That looks like a perfectly acceptable solution. If that works, use it. That is minimal code and there's no reason to optimize it unless you have to.

这看起来是完全可以接受的解决方案如果可行,请使用它。这是最小的代码,除非必须,否则没有理由对其进行优化。

#9


1  

Though I agree with scubabbl, here is a version without an inner while.

虽然我同意scubabbl,但这是一个没有内在的版本。

int year = 2008;
for (int m = Calendar.JANUARY; m <= Calendar.DECEMBER; m++) {
    Calendar cal = new GregorianCalendar(year, m, 1);
    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
    int diff = Calendar.FRIDAY - cal.get(Calendar.DAY_OF_WEEK);
    if (diff > 0) {
        diff -= 7;
    }
    cal.add(Calendar.DAY_OF_MONTH, diff);
    System.out.println(cal.getTime());
}

#10


1  

Slightly easier to read, brute-force approach:

稍微容易阅读,蛮力方法:

public int getLastFriday(int month, int year) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, month, 1, 0, 0, 0); // set to first day of the month
    cal.set(Calendar.MILLISECOND, 0);

    int friday = -1;
    while (cal.get(Calendar.MONTH) == month) { 
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { // is it a friday?
            friday = cal.get(Calendar.DAY_OF_MONTH);
            cal.add(Calendar.DAY_OF_MONTH, 7); // skip 7 days
        } else {
            cal.add(Calendar.DAY_OF_MONTH, 1); // skip 1 day
        }
    }
    return friday;
}

#11


1  

here's how to get the last friday, or whatever week day, of the month:

这是如何获得本月的最后一个星期五或任何工作日:

Calendar thisMonth = Calendar.getInstance();
dayOfWeek = Calendar.FRIDAY; // or whatever
thisMonth.set(Calendar.WEEK_OF_MONTH, thisMonth.getActualMaximum(Calendar.WEEK_OF_MONTH);;
thisMonth.set(Calendar.DAY_OF_WEEK, dayOfWeek);
int lastDay = thisMonth.get(Calendar.DAY_OF_MONTH); // this should be it.

#12


1  

Below program is for the last Friday of each month. it can be used to get the last of any day of the week in any month. The variable offset=0 means current month(system date), offset=1 means next month, so on. The getLastFridayofMonth(int offset) method will return the last Friday.

以下程序是每个月的最后一个星期五。它可用于获取任何一个月中任何一天的最后一天。变量offset = 0表示当前月份(系统日期),offset = 1表示下个月,依此类推。 getLastFridayofMonth(int offset)方法将返回上周五。

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class LastFriday {

  public static Calendar getLastFriday(Calendar cal,int offset){
    int dayofweek;//1-Sunday,2-Monday so on....
    cal.set(Calendar.MONTH,cal.get(Calendar.MONTH)+offset);
    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); //set calendar to last day of month
    dayofweek=cal.get(Calendar.DAY_OF_WEEK); //get the day of the week for last day of month set above,1-sunday,2-monday etc
    if(dayofweek<Calendar.FRIDAY)  //Calendar.FRIDAY will return integer value =5 
      cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)-7+Calendar.FRIDAY-dayofweek);
    else
      cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)+Calendar.FRIDAY-dayofweek); 

    return cal;
  }

  public static String  getLastFridayofMonth(int offset) { //offset=0 mean current month
    final String DATE_FORMAT_NOW = "dd-MMM-yyyy";
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
    cal=getLastFriday(cal,offset);
    return sdf.format(cal.getTime()); 

  }

  public static void main(String[] args) {
    System.out.println(getLastFridayofMonth(0)); //0 = current month
    System.out.println(getLastFridayofMonth(1));//1=next month
    System.out.println(getLastFridayofMonth(2));//2=month after next month
  }

}

#13


1  

In Java 8, we can do it simply as:

在Java 8中,我们可以简单地这样做:

LocalDate lastFridayOfMonth = LocalDate
                                    .now()
                                    .with(lastDayOfMonth())
                                    .with(previous(DayOfWeek.FRIDAY));

#14


0  

ColinD's solution shouldn't work: try running it with December 2008 and it'll try setting the 13th month of a year. However, replacing "cal.set(...)" with "cal.add(Calendar.MONTH, 1)" should work fine.

ColinD的解决方案不起作用:尝试在2008年12月运行它,它将尝试设置一年的第13个月。但是,将“cal.set(...)”替换为“cal.add(Calendar.MONTH,1)”应该可以正常工作。

#15


0  

public static int lastSundayDate()
{
    Calendar cal = getCalendarInstance();
    cal.setTime(new Date(getUTCTimeMillis()));
    cal.set( Calendar.DAY_OF_MONTH , 25 );
    return (25 + 8 - (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY ? cal.get(Calendar.DAY_OF_WEEK) : 8));
}

#16


0  

Hope this helps..

希望这可以帮助..

public static void getSundaysInThisMonth(int monthNumber, int yearNumber){
    //int year =2009;
    //int dayOfWeek = Calendar.SUNDAY;
    // instantiate Calender and set to first Sunday of 2009
    Calendar cal = new GregorianCalendar();
    cal.set(Calendar.MONTH, monthNumber-1);
    cal.set(Calendar.YEAR, yearNumber);
    cal.set(Calendar.DATE, 1);
    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
    int dateOfWeek = cal.get(Calendar.DATE);
    while (dayOfWeek  != Calendar.SUNDAY) {
       cal.set(Calendar.DATE, ++dateOfWeek);
       dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
      }
    cal.set(Calendar.DATE, dateOfWeek);

    int i = 1;
    while (cal.get(Calendar.YEAR) == yearNumber && cal.get(Calendar.MONTH)==monthNumber-1)
    {
            System.out.println("Sunday " + " " + i + ": " + cal.get(Calendar.DAY_OF_MONTH));
            cal.add(Calendar.DAY_OF_MONTH, 7);
            i++;
    }

  }
  public static void main(String args[]){
    getSundaysInThisMonth(1,2009);
  }

#17


-1  

public static Calendar getNthDow(int month, int year, int dayOfWeek, int n) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, month, 1);
    cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);
    cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, n);
    return (cal.get(Calendar.MONTH) == month) && (cal.get(Calendar.YEAR) == year) ? cal : null;
}

#1


24  

Based on marked23's suggestion:

基于标记23的建议:

public Date getLastFriday( int month, int year ) {
   Calendar cal = Calendar.getInstance();
   cal.set( year, month + 1, 1 );
   cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) );
   return cal.getTime();
}

#2


34  

Let Calendar.class do its magic for you ;)

让Calendar.class为你做神奇的事;)

pCal.set(GregorianCalendar.DAY_OF_WEEK,Calendar.FRIDAY);
pCal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);

#3


9  

You never need to loop to find this out. For determining the "last Friday" date for this month, start with the first day of next month. Subtract the appropriate number of days depending on what (numerical) day of the week the first day of the month falls on. There's your "last Friday." I'm pretty sure it can be boiled down to a longish one-liner, but I'm not a java dev. So I'll leave that to someone else.

你永远不需要循环来找到它。要确定本月的“上周五”日期,请从下个月的第一天开始。减去适当的天数,具体取决于每月第一天的某一天(数字)日期。这是你的“上周五”。我很确定它可以归结为一个冗长的单行程序,但我不是一个java开发人员。所以我会把它留给别人。

#4


8  

java.time

Using java.time library built into Java 8 and later, you may use TemporalAdjusters.lastInMonth:

使用Java 8及更高版本中内置的java.time库,您可以使用TemporalAdjusters.lastInMonth:

val now = LocalDate.now() 
val lastInMonth = now.with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY))

You may choose any day from the DayOfWeek enum.

您可以从DayOfWeek枚举中选择任何一天。

If you need to add time information, you may use any available LocalDate to LocalDateTime conversion like

如果您需要添加时间信息,可以使用任何可用的LocalDate到LocalDateTime转换

lastFriday.atStartOfDay() // e.g. 2015-11-27T00:00

#5


7  

I would use a library like Jodatime. It has a very useful API and it uses normal month numbers. And best of all, it is thread safe.

我会使用像Jodatime这样的库。它有一个非常有用的API,它使用正常的月号。最重要的是,它是线程安全的。

I think that you can have a solution with (but possibly not the shortest, but certainly more readable):

我认为你可以有一个解决方案(但可能不是最短的,但肯定更具可读性):

DateTime now = new DateTime();      
DateTime dt = now.dayOfMonth().withMaximumValue().withDayOfWeek(DateTimeConstants.FRIDAY);
if (dt.getMonthOfYear() != now.getMonthOfYear()) {
  dt = dt.minusDays(7);
}       
System.out.println(dt);

#6


2  

You need to know two things - the number of days in the month, and the weekday the first of the month falls on.

您需要知道两件事 - 本月的天数和本月的第一天的工作日。

If the first day of the month is a

如果该月的第一天是

  • Sunday, then the last Friday is always the 27th.
  • 星期天,那么最后一个星期五总是27日。

  • Monday, then the last Friday is always the 26th.
  • 星期一,那么最后一个星期五总是26日。

  • Tuesday, then the last Friday is always the 25th.
  • 星期二,那么上周五总是25日。

  • Wednesday, then the last Friday is the 24th, unless there are 31 days in the month, then it's the 31st
  • 星期三,那么最后一个星期五是24日,除非这个月有31天,那么它是第31天

  • Thursday, then the last Friday is the 23rd, unless there are 30 days or more in the month, then it's the 30th.
  • 星期四,那么最后一个星期五是23日,除非这个月有30天或更长时间,那么它是30日。

  • Friday, then the last Friday is the 22nd, unless there are 29 days or more in the month, then it's the 29th.
  • 星期五,那么最后一个星期五是22日,除非本月有29天或更长时间,那么它是第29天。

  • Saturday, then the last Friday is always the 28th.
  • 星期六,那么上周五总是28日。

There are only three special cases. A single switch statement and three if statements (or ternary operators if you like every case to have a single line...)

只有三个特例。一个switch语句和三个if语句(如果你喜欢每个case都有一行三元运算符......)

Work it out on paper. Don't need any special libraries, functions, julian conversions, etc (well, except to get the weekday the 1st falls on, and maybe the number of days that month... )

在纸上解决。不需要任何特殊的库,函数,朱利安转换等(好吧,除了让第一个工作日到来,也许那个月的天数......)

Aaron implemented it in Java.

Aaron用Java实现了它。

-Adam

#7


2  

code for Adam Davis's algorithm

Adam Davis算法的代码

public static int getLastFriday(int month, int year)
{
Calendar cal = Calendar.getInstance();
cal.set(year, month, 1, 0, 0, 0); // set to first day of the month
cal.set(Calendar.MILLISECOND, 0);

int firstDay = cal.get(Calendar.DAY_OF_WEEK);
int daysOfMonth = cal.getMaximum(Calendar.DAY_OF_MONTH);

switch (firstDay)
{
    case Calendar.SUNDAY :
        return 27;
    case Calendar.MONDAY :
        return 26;
    case Calendar.TUESDAY :
        return 25;
    case Calendar.WEDNESDAY :
        if (daysOfMonth == 31) return 31;
        return 24;
    case Calendar.THURSDAY :
        if (daysOfMonth >= 30) return 30;
        return 23;
    case Calendar.FRIDAY :
        if (daysOfMonth >= 29) return 29;
        return 22;
    case Calendar.SATURDAY :
        return 28;
}
throw new RuntimeException("what day of the month?");
}}

#8


1  

That looks like a perfectly acceptable solution. If that works, use it. That is minimal code and there's no reason to optimize it unless you have to.

这看起来是完全可以接受的解决方案如果可行,请使用它。这是最小的代码,除非必须,否则没有理由对其进行优化。

#9


1  

Though I agree with scubabbl, here is a version without an inner while.

虽然我同意scubabbl,但这是一个没有内在的版本。

int year = 2008;
for (int m = Calendar.JANUARY; m <= Calendar.DECEMBER; m++) {
    Calendar cal = new GregorianCalendar(year, m, 1);
    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
    int diff = Calendar.FRIDAY - cal.get(Calendar.DAY_OF_WEEK);
    if (diff > 0) {
        diff -= 7;
    }
    cal.add(Calendar.DAY_OF_MONTH, diff);
    System.out.println(cal.getTime());
}

#10


1  

Slightly easier to read, brute-force approach:

稍微容易阅读,蛮力方法:

public int getLastFriday(int month, int year) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, month, 1, 0, 0, 0); // set to first day of the month
    cal.set(Calendar.MILLISECOND, 0);

    int friday = -1;
    while (cal.get(Calendar.MONTH) == month) { 
        if (cal.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY) { // is it a friday?
            friday = cal.get(Calendar.DAY_OF_MONTH);
            cal.add(Calendar.DAY_OF_MONTH, 7); // skip 7 days
        } else {
            cal.add(Calendar.DAY_OF_MONTH, 1); // skip 1 day
        }
    }
    return friday;
}

#11


1  

here's how to get the last friday, or whatever week day, of the month:

这是如何获得本月的最后一个星期五或任何工作日:

Calendar thisMonth = Calendar.getInstance();
dayOfWeek = Calendar.FRIDAY; // or whatever
thisMonth.set(Calendar.WEEK_OF_MONTH, thisMonth.getActualMaximum(Calendar.WEEK_OF_MONTH);;
thisMonth.set(Calendar.DAY_OF_WEEK, dayOfWeek);
int lastDay = thisMonth.get(Calendar.DAY_OF_MONTH); // this should be it.

#12


1  

Below program is for the last Friday of each month. it can be used to get the last of any day of the week in any month. The variable offset=0 means current month(system date), offset=1 means next month, so on. The getLastFridayofMonth(int offset) method will return the last Friday.

以下程序是每个月的最后一个星期五。它可用于获取任何一个月中任何一天的最后一天。变量offset = 0表示当前月份(系统日期),offset = 1表示下个月,依此类推。 getLastFridayofMonth(int offset)方法将返回上周五。

import java.text.SimpleDateFormat;
import java.util.Calendar;

public class LastFriday {

  public static Calendar getLastFriday(Calendar cal,int offset){
    int dayofweek;//1-Sunday,2-Monday so on....
    cal.set(Calendar.MONTH,cal.get(Calendar.MONTH)+offset);
    cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); //set calendar to last day of month
    dayofweek=cal.get(Calendar.DAY_OF_WEEK); //get the day of the week for last day of month set above,1-sunday,2-monday etc
    if(dayofweek<Calendar.FRIDAY)  //Calendar.FRIDAY will return integer value =5 
      cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)-7+Calendar.FRIDAY-dayofweek);
    else
      cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)+Calendar.FRIDAY-dayofweek); 

    return cal;
  }

  public static String  getLastFridayofMonth(int offset) { //offset=0 mean current month
    final String DATE_FORMAT_NOW = "dd-MMM-yyyy";
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
    cal=getLastFriday(cal,offset);
    return sdf.format(cal.getTime()); 

  }

  public static void main(String[] args) {
    System.out.println(getLastFridayofMonth(0)); //0 = current month
    System.out.println(getLastFridayofMonth(1));//1=next month
    System.out.println(getLastFridayofMonth(2));//2=month after next month
  }

}

#13


1  

In Java 8, we can do it simply as:

在Java 8中,我们可以简单地这样做:

LocalDate lastFridayOfMonth = LocalDate
                                    .now()
                                    .with(lastDayOfMonth())
                                    .with(previous(DayOfWeek.FRIDAY));

#14


0  

ColinD's solution shouldn't work: try running it with December 2008 and it'll try setting the 13th month of a year. However, replacing "cal.set(...)" with "cal.add(Calendar.MONTH, 1)" should work fine.

ColinD的解决方案不起作用:尝试在2008年12月运行它,它将尝试设置一年的第13个月。但是,将“cal.set(...)”替换为“cal.add(Calendar.MONTH,1)”应该可以正常工作。

#15


0  

public static int lastSundayDate()
{
    Calendar cal = getCalendarInstance();
    cal.setTime(new Date(getUTCTimeMillis()));
    cal.set( Calendar.DAY_OF_MONTH , 25 );
    return (25 + 8 - (cal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY ? cal.get(Calendar.DAY_OF_WEEK) : 8));
}

#16


0  

Hope this helps..

希望这可以帮助..

public static void getSundaysInThisMonth(int monthNumber, int yearNumber){
    //int year =2009;
    //int dayOfWeek = Calendar.SUNDAY;
    // instantiate Calender and set to first Sunday of 2009
    Calendar cal = new GregorianCalendar();
    cal.set(Calendar.MONTH, monthNumber-1);
    cal.set(Calendar.YEAR, yearNumber);
    cal.set(Calendar.DATE, 1);
    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
    int dateOfWeek = cal.get(Calendar.DATE);
    while (dayOfWeek  != Calendar.SUNDAY) {
       cal.set(Calendar.DATE, ++dateOfWeek);
       dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
      }
    cal.set(Calendar.DATE, dateOfWeek);

    int i = 1;
    while (cal.get(Calendar.YEAR) == yearNumber && cal.get(Calendar.MONTH)==monthNumber-1)
    {
            System.out.println("Sunday " + " " + i + ": " + cal.get(Calendar.DAY_OF_MONTH));
            cal.add(Calendar.DAY_OF_MONTH, 7);
            i++;
    }

  }
  public static void main(String args[]){
    getSundaysInThisMonth(1,2009);
  }

#17


-1  

public static Calendar getNthDow(int month, int year, int dayOfWeek, int n) {
    Calendar cal = Calendar.getInstance();
    cal.set(year, month, 1);
    cal.set(Calendar.DAY_OF_WEEK, dayOfWeek);
    cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, n);
    return (cal.get(Calendar.MONTH) == month) && (cal.get(Calendar.YEAR) == year) ? cal : null;
}