Datetime 比较Groovy日期忽略日期
如何比较Groovy中的日期?如下所示:*MM-yyyy\u 1>MM-yyyy\u 2*您可以这样做:Datetime 比较Groovy日期忽略日期,datetime,groovy,Datetime,Groovy,如何比较Groovy中的日期?如下所示:*MM-yyyy\u 1>MM-yyyy\u 2*您可以这样做: 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( n
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)
}
}
您可以这样比较两个日期:
def myFormat = 'MM/dd/yyyy'
if(Date.parse(myFormat, '02/03/2012') >= Date.parse(myFormat, '03/02/2012))
{...}
谢谢我必须对此进行探讨,因为我对Groovy没有太多的想法,但我猜这是正确的方法。它基本上将两个日期的副本设置为每月的第一个,然后比较这些日期。。。如果设置了时间,请小心,因为这显然会影响事情。。。Groovy有一个很好的工具,如果时间是在约会中,而不是在比较中,您可能需要利用它