tags:

views:

94

answers:

5

I am trying to figure out the best way to determine if a given Date is 10 days or less from the end of the month. I am basically building functionality that will display a message if the month is almost over. Thanks!

+1  A: 

What about

def date = new Date();

// ten days is in the next month so we are near end of month
if ((date + 10).month != date.month) { 
    // write message
}

I'm a novice with groovy so I may have made a mistake with the syntax but the concept should be ok.

Michael Rutherfurd
Thanks Don. I didn't even think about the plus method being an operator overide.
Michael Rutherfurd
A: 

Michael Rutherfurd's suggestion groovyfied:

Date.metaClass.isEndOfMonth = { 
    (delegate+10).month != delegate.month
}

new Date().isEndOfMonth()
sbglasius
+2  A: 

An alternative would be something like:

def isEndOfMonth() {
  Calendar.instance.with {
    it[ DAY_OF_MONTH ] + 10 > getActualMaximum( DAY_OF_MONTH )
  }
}
tim_yates
A: 

The Joda Time library is well worth exploring. The author of Joda time is the spec lead of JSR-310 which aims to provide a Java 7 alternative to the "old" Calendar/Date classes.

import org.joda.time.*

@Grapes([
    @Grab(group='joda-time', module='joda-time', version='1.6.2')
])

DateTime now = new DateTime()
DateTime monthEnd = now.monthOfYear().roundCeilingCopy()
Days tendays = Days.days(10)

if (Days.daysBetween(now, monthEnd).isLessThan(tendays)) {
    println "Month is nearly over"
}
else {
    println "Plenty of time left"
}
Mark O'Connor
+1  A: 

Check out the Groovy Date Page.

boolean isLessThanNDaysFromEndOfMonth(Date d, int n) {
  return (d + n).month != d.month
} 
Yevgeniy Brikman