Inserting a Groovy Date into a Time Stamp Column

Groovy provides a great API for working with Date/Time values

Working with Dates in any language is one of those core fundamentals you need to know right away. Lucky for us, Groovy makes it super simple to work with dates. 

Working with Groovy Date

I am working on a project where I am using straight SQL to insert a record into a database using Groovy. It’s pretty darn easy in most languages to grab the current date/time and in Java, you can do so just by creating a new instance of the Date class.

The problem with this (and the same goes for other languages) is that you can’t insert that value into a timestamp column. I need to stick this date/time into a timestamp column and to do so in most languages you need to format this so it matches up to what a timestamp column expects. With this simple Java example, we need to bring in another package to do formatting, create a formatting object with the correct pattern and then format our date. Not the hardest thing in the world to do but certainly something I don’t care to do.

Luckily I am using Groovy on this project. If you haven’t already played around with Groovy it seems to remove the annoyances of Java by adding on to the API. Groovy adds a convenient method to all Date objects for converting a date to a timestamp. If you print out the class names you will also see that it’s not just converting it into a formatted string but an actual timestamp object.  No extra libraries needed and I don’t have to remember what a timestamp format looks like.

To me, this is just one in the land of many examples of how Groovy makes programming in Java fun.

Question: What are some of the other ways Groovy makes your life easier? 

Hi, I’m Dan Vega. I am a Software Engineer living just outside of one of my favorite places in the world, Cleveland, Ohio. I am a self-taught programmer who firmly believes that you can accomplish anything in this life if you put your mind to it, roll up your sleeves and are willing to put in the work.

I have been writing software for over 18+ years now and I use my knowledge, passion, and influence to help other developers achieve their goals. I teach online and currently, have over 30,000 students.

When I am not writing software, I have a number of things that really keep me busy. I love to read books, listen to podcasts and watch online courses. I have a real thirst for knowledge and it consumes me every single day of the week. I also love to run & lift heavy weights which keep me balanced throughout the week.

Please note: I reserve the right to delete comments that are offensive or off-topic.