Groovy Tips for date and list

Posted By : Shiv Kumar | 29-Sep-2014

Some useful groovy tips  : 

1. List Size : Often we used to find list is empty or not. For this we do something like :

	List numberList = [1,2,3]  // list in this case
	if(numberList.size() == 0){
	...
	}
	else{
	...
	}

Rather than doing this, we can simply use groovy advancement like :

	if(!numberList){   // checks is list empty?
	...
	}
	else{
	...
	}

2. Finding current day,month and year from the date : 

 As Date methods are deprecated to find out current day, month and year from date object and other information.

We can use Calender Object for this like (current date is 29/08/2014):

	Calendar now = Calendar.getInstance()   // Gets the current date and time.
	def year= now.get(Calendar.YEAR);       // year = 2014

	def month= now.get(Calendar.MONTH)+1 ; // month = (8+1) = 9
	// Reason for incrementing by 1 is that first month of the year in the Gregorian and Julian calendars is JANUARY which is 0; the last
	depends on the number of months in a year.
	So if your current date is 29/08/2014 then it will return month as 8.

	def day = now.get(Calendar.DAY_OF_MONTH)  // day = 29

You can also find more information about zone, week of year,week of month and hour of day etc. from Calender object

Thanks

Shiv Kumar