1

如何在 Groovy 中忽略日期比较日期?像这样:*MM-yyyy_1 > MM-yyyy_2*

4

2 回答 2

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( 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)
          }
}
于 2012-05-23T09:00:03.373 回答
1

您可以像这样比较两个日期:

def myFormat = 'MM/dd/yyyy'
if(Date.parse(myFormat, '02/03/2012') >= Date.parse(myFormat, '03/02/2012))
{...}
于 2012-05-23T09:02:50.427 回答