RyanLynch
RyanLynch

Reputation: 3007

Determine if the month is almost over in Groovy

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!

Upvotes: 2

Views: 374

Answers (5)

Yevgeniy Brikman
Yevgeniy Brikman

Reputation: 9381

Check out the Groovy Date Page.

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

Upvotes: 1

Mark O'Connor
Mark O'Connor

Reputation: 78011

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"
}

Upvotes: 0

tim_yates
tim_yates

Reputation: 171164

An alternative would be something like:

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

Upvotes: 2

sbglasius
sbglasius

Reputation: 3124

Michael Rutherfurd's suggestion groovyfied:

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

new Date().isEndOfMonth()

Upvotes: 0

Michael Rutherfurd
Michael Rutherfurd

Reputation: 14065

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.

Upvotes: 1

Related Questions