2012-05-23 116 views

回答

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) 
      } 
} 
+0

谢谢!由于我没有用Groovy思考过很多东西,所以我将不得不探讨这一点,但我猜测这是正确的方法。 – drago

+1

它基本上将这两个日期的副本设置为本月的第一个日期,然后比较这些日期...谨慎设置时间,因为显然这会影响事物... Groovy有一个['Date.clearTime ()'方法](http://groovy.codehaus.org/groovy-jdk/java/util/Date.html#clearTime%28%29),你可能需要使用,如果时间将会在你的日期,但不是你的比较 –

1

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

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