String -> java.util.Date -> java.sql.Date (with time stamp)

akwarywo picture akwarywo · Dec 21, 2012 · Viewed 41.1k times · Source

Here is my problem: I have a user input a date like: 2012-12-24 (string) I concatenate a time to that string, and convert to java.util.Date My code looks like:

String tempstartdate = startdte;  //startdte is the string value from a txtfield
       tempstartdate += " 00:01:00";
       String tempenddate = startdte;
       tempenddate += " 23:59:59";

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");               
       java.util.Date validstartdte = null;
        java.util.Date validenddte = null;

validstartdte = df.parse(tempstartdate);  //validstartdte is a util.Date (and works)
validenddte = df.parse(tempenddate);

My problem is, when I take that util.Date and want to make it an sql.Date:

java.sql.Date sqlstartDate = new java.sql.Date(validstartdte.getTime());
java.sql.Date sqlendDate = new java.sql.Date(validenddte.getTime());

It will not give me the timestamp I assigned, it will only return the date in the form yyyy-MM-dd (such as 2012-12-23).

WHY!? I'm so frustrated.
Note: I noticed that when I used breakpoints, I was able to expand sqlendDate and see there is a value in there called cdate that returns: 2012-12-12T23:59:59.000-0500 The database I'm using is PostgreSQL.

Please help! Much appreciated.

Answer

Felipe Fonseca picture Felipe Fonseca · Dec 21, 2012

java.sql.Date doesn't have the time.

Use java.sql.Timestamp instead.