Posts

Showing posts from June, 2009

Java Dates: java.util.Date, java.sql.Date, java.util.Calendar

Working with dates in Java (though not limited to Java) has always been a nightmare. There are lots of good articles out there in Google Land on the topic, but after some very good questions from my class, I thought I'd add my two-cents and code samples to the mix. Much of the confusion centered around conversion, so here's some basic how-to snippits: Convert java.util.Calendar to java.util.Date: java.util.Calendar calendar = java.util.Calendar.getInstance(); java.util.Date utilDate = calendar.getTime(); //or by using the constructor java.util.Date utilDate = new java.util.Date(calendar.getTimeInMillis()); Convert java.util.Date to java.sql.Date: java.util.Date utilDate = java.util.Calendar.getInstance().getTime(); java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); Convert java.util.Calendar to java.sql.Date: java.util.Calendar calendar = java.util.Calendar.getInstance(); java.sql.Date utilDate = new java.sql.Date(calendar.getTimeInMillis()); Here we have to create...