有人知道在 Groovy 中计算每月第 n 个工作日的最佳方法吗?
即2011 年 4 月 (4) 的第 7 个工作日为 4 月 11 日。
最佳答案
我写了一个quick DSL for working with days (链接示例显示计算英国假期)
使用它,要查找(例如)今年(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 ]
哪个打印(如你所愿)
Mon Apr 11 00:00:00 UTC 2011
因为您可能没有月份名称而是整数,您可以将调用包装在一个函数中:
// 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 )
如果您不想使用它(对于这个特定问题,它可能过于复杂),您将回到使用 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 ]
或
def weekdays = new WeekdayIterator( Calendar.APRIL, 2011 )
println weekdays.iterator()[ 6 ]
关于java - 在 Groovy 中查找一个月的第 n 个工作日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7163716/