Skip to Content
If you have just started using java, you might not be aware of different types available in java to handle time and dates. So, you looked on internet or referred some book and decided to use a particular type say ‘java.sql.Date’. Now after substantial development has been done, you have got scenarios where you realize that you should have used a different format. For example … exposing the functionality as web service, which actually does not support this ‘java.sql.Date’ but ‘java.util.Date’. Also, you realize that many methods for these classes have been deprecated and you don’t have many ways to manipulate your date objects. In such cases you again start looking for other classes that will suit your requirements better. Or may be you look for some ways for casting or converting an object to a different object of some other class. While development I have faced many problems, though small, with these classes. So, here’s the list of types and conversion methods.

Introduction to Types

Java provides you with multiple classes to handle time and dates.

  1. java.sql.Date – This is the a simple date which has day, month and weeks. All the hrs, mins and seconds are 00:00:00 and cannot be changed.
    Format: 2001-10-21 00:00:00
  2. java.util.Date – This is a little better date format which holds the time conponent as well and is really helpful if you want to store both date and time together.
    Format: 2001-10-21 12:19:29
  3. java.sql.Timestamp – An another bigger date format which is infact a composite of java.util.Date and a separate nanoseconds component.
    Format: 2001-10-21 12:19:29.273839118
  4. java.util.Calendar -Apart from all these there is another abstract class java.util.Calendar, which is very helpful when you need to handle Timezones as well. There is no format for this , just the fact that it stores everything that you can think for Time.

Converting between the formats

java.util.Date utilDate = new java.util.Date( ); java.sql.Date sqlDate = new java.sql.Date( ); java.sql.Timestamp timestamp = new java.sql.Timestamp( ) ; java.util.Calendar cal = Calendar.getInstance( );

  • From Calendar
    1. utilDate = new java.util.Date( cal.getTime( ) );
    2. sqlDate = new java.sql.Date( cal.getTime().getTime() );
    3. sqlDate = java.sql.Date.valueOf( cal.get(cal.YEAR) + “:” + cal.get(cal.MONTH) + “:” + cal.get(cal.DATE) );
  • From util Date
    1. sqlDate = new java.sql.Date ( utilDate.getTime( ) );
    2. timestamp = new java.sql.Timestamp( utilDate.getTime( ) );
  • From sql Date
    1. utilDate = Timestamp.valueOf(sqlDate.toString() + ” 00:00:00.000″ );
    2. utilDate = Timestamp.valueOf( cal.get(cal.YEAR) + “-” + cal.get(cal.MONTH) + “-” + cal.get(cal.DATE) + ” 00:00:00.000″);
To report this post you need to login first.

Be the first to leave a comment

You must be Logged on to comment or reply to a post.

Leave a Reply