Date methods in groovy

Posted By : Varun Sharma | 14-Apr-2014

There are certain situations where we need to have some functions to be performed on Date objects, groovy provides you some excellent methods for various operations.

  • upto: This method allows you to iterate from given date to the current date just by incrementing the value by one.
  • downto:  This method allows you to iterate from current date/given date to the other date just by decrementing the value by one.
Date previousDate = new Date()
Date currentDate = new Date()

previousDate.upto(currentDate) { it ->
it-> represents date object.
}

currentDate.downto(previousDate) { it ->
it-> represents date object.
}
  • minus: Subtract number of days from given date & will return you new date.
  • plus: Add number of dayes to date object & it will give you new date.
// minus
def today = new Date()
def yesterday = today - 1

// plus
def today = new Date()
def tomorrow = today + 1
  • previous: After applying on any date object gives you previous date.
  • next: After applying on any date object gives you a next date.
// previous()
Date today = new Date()
Date yesterday = today.previous()

// next()
Date today = new Date()
Date tomorrow = today.next()
  • toCalendar: This method converts a Date object to Calendar object.  
def dateObject = new Date()
def calendarObject = today.toCalendar()

>Hope it helps !

Varun Sharma [email protected]

http://oodlestechnologies.com/

About Author

Author Image
Varun Sharma

Varun is an experienced Groovy and Grails developer and has worked extensively on designing and developing applications with FaceBook , Linkedin and Twitter integrations using Grails technologies. Varun loves painting and photography.

Request for Proposal

Name is required

Comment is required

Sending message..