Sunday, March 23, 2014
This is a very popular question often asked in an interview. You also might be in a situation where you have to store the current date retrieved by java.util.Date in a database table where the datatype of the column is DATE . In that case you have to convert it to java.sql.Date . Also you might have to fetch date from database and then store it in a java.util.Date object . So this is a very important topic. Since both of these classes store the value of date in long milliseconds, so it is very easy to convert from one type to the other. Both of these classes have a method called getTime() which is used for conversion.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
public class DateConverter {

    public static void main(String[] args) {
      
        //creating instances of java.util.Date representing current date and time
        java.util.Date now = new java.util.Date();
        System.out.println("Value of java.util.Date : " + now);
      
        //converting java.util.Date to java.sql.Date in Java
        java.sql.Date sqlDate = new java.sql.Date(now.getTime());
        System.out.println("Converted value of java.sql.Date : " + sqlDate);
      
        //converting java.sql.Date to java.util.Date back
        java.util.Date utilDate = new java.util.Date(sqlDate.getTime());
        System.out.println("Converted value of java.util.Date : " + utilDate);
    }
}
-------------------------------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------------------------------
Value of java.util.Date : Sun Mar 23 11:35:46 IST 2014
Converted value of java.sql.Date : 2014-03-23
Converted value of java.util.Date : Sun Mar 23 11:35:46 IST 2014


Hope this helps. Happy coding :)

0 comments:

Post a Comment

Total Pageviews

Subscribe via Email

Followers


Popular Posts

About Me

My photo

I am a student of BTech Computer Science Engineering from RCCIIT,Kolkata. I am a crazy lover of Java and wants to settle as a Java developer. I have a seven years Java experience with an application developer experience for 2 years. Recently from March 2012 I am a registered S40 app developer for Nokia and has corrected an app of them. I am currently writing blogs to encourage and grow interest in all those who don't know or learning Java.