你可以做到这一点:
int compareIgnoringDays( Date a, Date b ) {
new Date( a.time ).with { newa ->
new Date( b.time ).with { newb ->
newa.set( date:1 )
newb.set( date:1 )
newa.compareTo( newb )
}
}
}
你可以测试一下:
Date a = Date.parse( yyyy/MM/dd , 2012/05/23 )
Date b = Date.parse( yyyy/MM/dd , 2012/05/24 )
Date c = Date.parse( yyyy/MM/dd , 2012/06/01 )
assert compareIgnoringDays( a, b ) == 0
assert compareIgnoringDays( b, a ) == 0
assert compareIgnoringDays( a, c ) == -1
assert compareIgnoringDays( c, a ) == 1
另一种不同的写法是:
int compareIgnoringDays( Date a, Date b ) {
[ a, b ].collect { new Date( it.time ) } // Clone original dates
.collect { it.set( date:1 ) ; it } // Set clones to 1st of the month
.with { newa, newb ->
newa.compareTo( newb ) // Compare them (this gets returned)
}
}