All Things Techie With Huge, Unstructured, Intuitive Leaps

Java - Convert Gregorian Calender to DateTime

When programming in Java, I like java.util.GregorianCalendar a lot. It makes date and time manipulation easy peasy. For example, I have an application where I have to get the current datetime and add twenty minutes. It happens in a couple of lines:

GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
gc.set(GregorianCalendar.MINUTE, +20);

Piece of cake. But when I wanted to take the manipulated time and cache it back to the database (mysql), I was stymied for a moment. The database field was a datetime entity, and for a few minutes I wondered how to convert Gregorian Calendar to DateTime.

I didn't realize the relationship between DateTime and TimeStamp, so it took me a few minutes longer to figure out. The piece of code that eventually worked was:

GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
gc.set(GregorianCalendar.MINUTE, +20);
java.sql.Timestamp javaSqlTS = new java.sql.Timestamp(gc.getTimeInMillis());

Hope this helps someone Googling how to convert Gregorian Calendar into DateTime for SQL.


2 comments: