Java 在Groovy中查找当月第n个工作日

Java 在Groovy中查找当月第n个工作日,java,date,groovy,Java,Date,Groovy,有人知道在Groovy中计算每月第n个工作日的最佳方法吗 i、 e.2011年4月4日的第7个工作日是4月11日。我写了一篇文章(链接的例子显示了如何安排英国假期) 使用该方法,要查找(例如)今年(2011年)9月的第5个工作日,您可以执行以下操作: // 5th weekday in September println new DateDSL().with { every.weekday.in.september( 2011 ) }[ 4 ] 哪张照片 Wed Sep 07 00:00:

有人知道在Groovy中计算每月第n个工作日的最佳方法吗

i、 e.2011年4月4日的第7个工作日是4月11日。

我写了一篇文章(链接的例子显示了如何安排英国假期)

使用该方法,要查找(例如)今年(2011年)9月的第5个工作日,您可以执行以下操作:

// 5th weekday in September
println new DateDSL().with {
  every.weekday.in.september( 2011 )
}[ 4 ]
哪张照片

Wed Sep 07 00:00:00 UTC 2011
使用您的示例,您将执行以下操作:

// 7th Weekday in April
println new DateDSL().with {
  every.weekday.in.april( 2011 )
}[ 6 ]
哪种打印(如您所需)

由于您可能没有按名称而是按整数来表示月份,因此可以将调用封装在函数中:

// n and month starts from 1 (for first day/month)
Date nthWeekdayInMonth( int n, int month, int year ) {
  new DateDSL().with {
    every.weekday.in."${months[month-1]}"( year )
  }[ n - 1 ]
}

println nthWeekdayInMonth( 7, 4, 2011 )
如果您不想使用它(对于这个特定的问题,可能已经超过了comlpex),那么您可以重新使用java日历并滚动日期(就像在dsl的工作中那样)


编辑 一种不太复杂的方法可能是创建一个在工作日内迭代的类,如下所示:

class WeekdayIterator {
  private static GOOD_DAYS = [Calendar.MONDAY..Calendar.FRIDAY].flatten()
  private Calendar c = Calendar.instance
  private Date nxt
  private int month, year

  WeekdayIterator( int month, int year ) {
    c.set( year, month, 1 )
    this.month = month
    nxt = nextWeekday()
  }
  private Date nextWeekday() {
    while( c.get( Calendar.MONTH ) == month ) {
      if( c.get( Calendar.DAY_OF_WEEK ) in GOOD_DAYS ) {
        Date ret = c.time.clearTime()
        c.add( Calendar.DATE, 1 )
        return ret
      }
      c.add( Calendar.DATE, 1 )
    }
    null
  }
  Iterator iterator() {
    [ hasNext:{ nxt != null }, next:{ Date ret = nxt ; nxt = delegate.nextWeekday() ; ret } ] as Iterator
  }
}
然后可以这样调用,通过以下方式获得第7个工作日:

def weekdays = new WeekdayIterator( Calendar.APRIL, 2011 )
println weekdays.collect { it }[ 6 ]


只是一个提示:这取决于国家(阿拉伯国家的节假日、周末等各不相同)。这也会因公司而异。有些在感恩节后第二天就关门了,有些则不然。谢谢蒂姆,这是一个很好的回答。我将看看是否可以在Eire假日中实现它——当前应用程序正在从属性文件中读取这些内容。(我会在stackoverflow认为我有足够的荣誉时投票支持该回复)
def weekdays = new WeekdayIterator( Calendar.APRIL, 2011 )
println weekdays.collect { it }[ 6 ]
def weekdays = new WeekdayIterator( Calendar.APRIL, 2011 )
println weekdays.iterator()[ 6 ]