比较Groovy日期忽略天数

时间:2012-05-23 08:52:23

标签: datetime groovy

如何比较Groovy忽略日期的日期?这样的事情: * MM-yyyy_1> MM-yyyy_2 *

2 个答案:

答案 0 :(得分: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)
          }
}

答案 1 :(得分:1)

您可以比较两个日期:

def myFormat = 'MM/dd/yyyy'
if(Date.parse(myFormat, '02/03/2012') >= Date.parse(myFormat, '03/02/2012))
{...}