Groovy

Groovy Date Example

1. Introduction

Date operations may be painful in most of the programming languages. You may spend most of your time to convert dates from one format to another one. In Groovy, date operations are very easy. Groovy has lots of functions extended from JDK Date API, this allows us to use date related operations in an easier way. Let’s have a look at how can we use Groovy date extension.

2. Warmup

In Java, we use Date or Calendar in for specific cases. Date class is a simple class and it has backward compatibility. If you want to do some date arithmetic operations, use Calendar class instead. In Groovy, we can use both Date or Calendar. You can see following example for initializing and getting current date.

 
GroovyDateInitialization.groovy

package com.javacodegeeks.groovy.date

import static java.util.Calendar.*

class GroovyDateInitialization {

	static main(args) {
		def date = new Date()
		println date // Sat Sep 26 19:22:50 EEST 2015
		
		def calendar = Calendar.instance
		println calendar // java.util.GregorianCalendar[time=1443284933986, ...
	}

}

As you can see, date variable is a simple date, but calendar has a value class with some instance variables. I have provided only one instance variable, because it is very long. This is simple in Java too, but what about parsing?

3. Date Parsing

Date parsing is the operation of conversion date string to date object. You can simply parse date string to date object easily like below.

GroovyDateParsing.groovy

package com.javacodegeeks.groovy.date

import static java.util.Calendar.*

class GroovyDateParsing {

	static main(args) {
		def date = new Date().parse("dd.MM.yyy", '18.05.1988')
		println date // Wed May 18 00:00:00 EEST 1988
		
		def extendedDate = new Date().parse("dd.MM.yyy HH:mm:ss", '18.05.1988 12:15:00')
		println extendedDate // Wed May 18 12:15:00 EEST 1988
	}

}

On line 08, we used parse function to parse provided date string by using date format provided as first argument. In line 11, hour, minute, and seconds parameters provided in the format and date string in order to be parse extended date. In first example on line 08, it printed 00:00:00, because we did not provided hour, minute, and seconds section. You can have a look at here to see full date formats.

4. Date Formatting

Sometimes, we need to format date object into desired format. In Groovy, you can use format function to format date object. You can see a quick example below.

GroovyDateFormatting.groovy

package com.javacodegeeks.groovy.date

import static java.util.Calendar.*

class GroovyDateFormatting {

	static main(args) {
		def date = new Date().parse("dd.MM.yyy", '18.05.1988')
		def formattedDate = date.format("dd/MM/yyy")
		println formattedDate // 18/05/1988
	}

}

In this example, we simply parsed the date string into a date object on line 08, and then we have formatted that date object by using format function on line 09. In order to format a date object, you can provide date format as argument.

5. Date Arithmetic

The main advantage of the Groovy date extension is the doing arithmetic operations on date object. If you have used Joda Time before, you will be very familiar to this topic. Let say that, you have a date and you want to find the date object which is 5 days after from previous date. In order to do that, you can use following example.

GroovyDateArithmetic.groovy

package com.javacodegeeks.groovy.date

class GroovyDateArithmetic {

	static main(args) {
		def date = new Date().parse("dd.MM.yyy", '18.05.1988')
		
		def datePlus = date.clone()
		def dateMinus = date.clone()
		
		datePlus = datePlus + 5
		
		println datePlus // Mon May 23 00:00:00 EEST 1988
		
		datePlus = datePlus.plus(5)
		
		println datePlus // Sat May 28 00:00:00 EEST 1988
		
		dateMinus = dateMinus - 10
		
		println dateMinus // Sun May 08 00:00:00 EEST 1988
		
		dateMinus = dateMinus.minus(10)
		
		println dateMinus // Thu Apr 28 00:00:00 EEST 1988
		
		def dateInterval =  dateMinus..<datePlus
		
		println dateInterval // [Thu Apr 28 00:00:00 EEST 1988,.., Fri May 27 00:00:00 EEST 1988]
	}

}

In above example, we have done some arithmetic operations. First, we have cloned date to two variables dateMinus, and datePlus to simulate two different dates. In order to increment date object by 5 days, we have used datePlus = datePlus + 5 on line 11. Alternatively you can use plus function like on line 15. In same way, we have decremented the dateMinus by 10 by using subtracting sign in dateMinus = dateMinus - 10. Alternatively, you can use minus function like on line 23. We have also find the dates between two dates dateMinus and datePlus by using the range(..) function in Groovy. You can see the date ranges on line 29.

6. Subscript Operators

In some cases, you may need to get year, month, date values separately from date objects, or you may need to set those fields in date objects separately. Subscript operators helps us to get that specific values. In fact, Groovy uses getAt() and putAt() respectively to get and set specific subscript fields in date object. Let’s see some examples.

GroovyDateSubscriptOperators.groovy

package com.javacodegeeks.groovy.date

import static java.util.Calendar.*

class GroovyDateSubscriptOperators {

	static main(args) {
		def date = new Date().parse("dd.MM.yyy", '18.05.1988')
		
		println date[YEAR] // 1988
		println date[MONTH] // 4
		println date[DATE] // 18
		
		date[YEAR] = 1999
		date[MONTH] = 7
		date[DATE] = 20
		
		println date // Fri Aug 20 00:00:00 EEST 1999
	}

}

In this example, on line 10, 11, and 12 we get the year, month, and day value from date object. This is something like getting value from map by providing the map key. But, where did YEAR, MONTH, and DATE come from? They come from the static import import static java.util.Calendar.* on line 03. Be careful about the month value on line 11, and it is the index of the month. You can also set month, year, and day values like setting a map on line 14, 15, and 16.

7. Conclusion

Date operations are the operations that we used during software development and it is really painful on converting dates from one format to another. In Groovy, this operations are very simplified, and you can easily perform date operations like applying arithmetic in Math. You can parse date string, format a date object, increment – decrement date, and apply subscript operators on date objects without using any third party libraries.

Download
You can download the full source code of the project here: GroovyDateExample

Huseyin Babal

Huseyin Babal has deep experience in Full Stack Development since 2007. He is mainly developing applications with JAVA, Spring, PHP, NodeJS, AngularJS. He is also interested in DevOps Engineering since 2013 and using AWS, Heroku for Cloud deployment and playing with Docker and Consul for implementing infinite scalable systems. He likes to share his experience in public conferences and perform advanced workshops about Full Stack Development and Devops. He is the author of NodeJS in Action course in Udemy.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button