Manisha, yesterday I had do build a new version of the class, capable of handling
null Date objects. Here it goes, in case you or anyone else wants to use it:
import java.util.Date;
/**
* This class is used to avoid date manipulation errors found in some Relational
* Database Management Systems or their JDBC drivers. These limitations may
* cause the date to be stored slightly different than it exists in the JVM,
* sometimes with a small milisecond difference.<br>
* <br>
* The use of this class ensures that java.util.Date objects are able to be stored
* in their natural format (a long number) in any RDBMS that supports String
* columns (all of them).<br>
* <br>
* It also supports the storage of null Date objects.
* @author Fabio Luis De Paoli
* @since 2-Mar-2001
* @version 1.1
*/
public class DateSQLStringWrapper
{
private static final String zeroes = "0000000000000000000";
public Date toDate(String aStr) {
if (aStr.substring(0,5).equals("Anull")) return null;
try {
long tempLong;
tempLong = (Long.valueOf(aStr.substring(1,20))).longValue();
if (aStr.substring(0,1).equals("N")) tempLong = tempLong * (-1L);
return new Date(tempLong);
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
throw new InternalError(nfe.getMessage());
}
}
/**
* This method will transform a Date into a 20 character long String
* in the format:<br>
* <br>
* SNNNNNNNNNNNNNNNNNNN<br>
* <br>
* Where:<br>
* <ul><li>S will contain P for positive, N for negative. This ensures correct
* sorting of dates, because N comes before P. Zero is considered positive.
* <li>NNNNNNNNNNNNNNNNNNN will contain zero padded, nineteen digit, string
* translation of the Date's internal long number.
* </ul>
* For example, the Date "2001-Feb-19 0:00:00.000 GMT-3" will become the String
* "P0000000982591200000".
* <br>
* Obs: if the supplied Date is null, the resulting string is "Anull", which will
* sort before the smallest possible date.
*/
public String toStr(Date aDate) {
if (aDate == null) return "Anull";
> mhadke@yahoo.com wrote:
>
> > i want to put java date(actually time from 1 jan, 1970) into sql database(sql
> > 6.5 server). what should be type of that field in sql table? how to store
> > java obj into it? does sql6.5 server support BIGINT that is given in JDBC
> > book? do i have to use a driver other that jdbcdbc?
> >
> > -manisha
>
> You should use some type of "timestamp" column, and store the java.util.Date as a
> java.sql.Date or java.sql.Timestamp object.
>
> However WATCH OUT for:
> - buggy jdbcs that incorrectly add one or two miliseconds to your Date during the
> insert or the read operation
> - buggy jdbcs that use the default Timezone to translate your Date's value to
> GMT+0 when storing data, but not when reading it (ARGH... happened to me)
>
> I grew tired of playing with databases and JDBCs and decided to wrap the Date
> into a String, using the class below. Feel free to use it.
Bookmarks