March 28, 2016

Convert java.util.Date > java.sql.Date > java.sql.Timestamp > java.text.SimpleDateFormat

java.util.Date : The class Date represents a specific instant in time, with millisecond precision.

Code :
 java.util.Date dtUtil = new java.util.Date();  
Output :
Mon Mar 28 21:35:05 IST 2016

java.sql.Date : A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.

To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

long java.util.Date.getTime() :
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by Date object.

Code : Convert java.util.Date to java.sql.Date
 java.sql.Date dtSql = new java.sql.Date(dtUtil.getTime());  
Output :

java.sql.Timestamp : A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value. It adds the ability to hold the SQL TIMESTAMP fractional seconds value, by allowing the specification of fractional seconds to a precision of nanoseconds.

Code :
 java.sql.Timestamp dtTime = new java.sql.Timestamp(dtUtil.getTime());  
Output :
2016-03-28 21:35:05.181

java.text.SimpleDateFormat : SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date ? text), parsing (text ? date), and normalization.

Code :
 SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");  
 String dt = sdf.format(dtTime);
Output :
28-03-2016 21:35:05



We shall not be liable for the improper or incomplete transmission of the information contained in this communication nor for any delay in its response or damage to your system. We do not guarantee that the integrity or security of this communication has been maintained or that this communication is free of viruses, interceptions or interferences. Anyone communicating with us by email accepts the risks involved and their consequences. We accept no liability for any damage caused by any virus transmitted by this site.