Casting an sql.Date to an util.Date and vice versa

Without going into depth about the Localization issues that might occur when doing this I’d like to state how you can “cast” a java.util.Date that might be risen by your application logic to a java.sql.Date that you might need for a prepared statement. To convert both with each other you can use the microtime that both types understand. To retrieve the microtime of a given date Java has it’s built-in Calendar class that holds for localization and date transformation features not to be mentioned here.

java.util.Date utlDate = new java.util.Date;
Calendar stCal = Calendar.getInstance();

stCal.setTime(utlDate);
java.sql.Date sqlDate = new java.sql.Date(stCal.getTimeInMillis());

and you’re done. The other way round should work either.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s