Convert string into java.sql.Date

Hi,
I want to convert a date in string form into java.sql.Date to persist into the database column with Date as its datatype in Oracle. I'm trying as follows:
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class DateTest
public static void main(String[] args)
String strDate = "2002-07-16 14:45:01";
     System.out.println("strDate = "+strDate);
Date aDate = null;
try
if(strDate != null && !strDate.trim().equals(""))
     SimpleDateFormat aSDF = new SimpleDateFormat();
     aSDF.applyPattern("yyyy-MM-dd hh:mm:ss");
     java.util.Date utilDate = aSDF.parse(strDate);
System.out.println("utildate = "+utilDate);
     aDate = new Date(utilDate.getTime());
     aDate.setTime(utilDate.getTime());      
     System.out.println("aDate = "+aDate);
catch (ParseException e)
System.out.println("Unable to parse the date - "+strDate);
catch (Exception ex)
ex.printStackTrace();
System.out.println("Caught Exception :"+ex.getMessage());
It gives the output as :
strDate = 2002-07-16 14:45:01
utildate = Tue Jul 16 14:45:01 IST 2002
aDate = 2002-07-16
If I put this value into the database table, I can see only the date. Time part is missing. Is this the problem with java.sql.Date or Oracle datatype Date? Please help me asap.
Thanks in advance.
Regards,
Rajapriya.R.

If I put this value into the database table, I can
see only the date. Time part is missing. Is this the
problem with java.sql.Date or Oracle datatype Date?This is not a problem, this is the defined behaviour of the Date type. RTFAPI and have a look at Timestamp, while you're at it.

Similar Messages

  • String into java.sql.Date

    Can anyone tell me how to convert a String (yyyy-mm-dd) into a java.sql.Date format? Also I need to test to see if the Date of birth (entered in the format above) is >= 18.
    Can I do this in an SQL query?
    Thanks
    Marika Ludmann

    Can anyone tell me how to convert a String
    (yyyy-mm-dd) into a java.sql.Date format? Also I need
    to test to see if the Date of birth (entered in the
    format above) is >= 18.
    Can I do this in an SQL query?
    Thanks
    Marika LudmannTry this:
       String dateStr = "2003-04-29";
       SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
       Date result = formater.parse(dateStr);Don't forget to add the
    import java.text.SimpleDateFormat;

  • Needed help regarding converting  string to java.sql.Date format

    I have a a function which returns a calendar object. The date must be inserted to Oracle DB using java.sql.Date format.
    So i have converted the Calendar object to java.sql.Date format using the following code
    java.sql.Date publicationDate = new java.sql.Date(book.getPublicationDate().getTime().getTime());But while getting inserted into the DB it was in mm/dd/yyyy format whereas i wanted dd/mm/yyyy format
    Can any body please help out how to store the date in dd/mm/yyyy format ?

    Can u please explain this a bit
    This is my code
    public int addBook(List<Book> BookList) throws SQLException, ParseException{
              System.out.println("Hi there");
              Book book = new Book();
              BookDB bookDb = new BookDB();
              //listLength =      BookList.length;
              String bookId = null;
                   try{
                        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
                        con  = DriverManager.getConnection("jdbc:oracle:thin:@10.123.79.195:1521:findb01","e115314", "e115314");
                        addBook = con.prepareStatement("insert into ABC_Book values(?,?,?,?,?,?,?)");
                        Iterator<Book> iterator = BookList.iterator();
                        while(iterator.hasNext()){
                             book = (Book)iterator.next();
                             System.out.println(book.getBookId());
                             addBook.setString(1,book.getBookId());
                             addBook.setString(2,book.getTitle());
                             addBook.setString(3,book.getAuthor());
                             addBook.setString(4,book.getPublisher());
                             System.out.println(book.getPublicationDate());
                             System.out.println("Before Date");
                             System.out.println("book.getPublicationDate().getTime()"+book.getPublicationDate().getTime());
                             java.sql.Date publicationDate = new java.sql.Date(book.getPublicationDate().getTime().getTime());
                             SimpleDateFormat formatter = new SimpleDateFormat("dd/mm/yyyy");
                             dateString = formatter.format(publicationDate);
                             System.out.println("Today is"+dateString);
                             java.sql.Date date = (java.sql.Date)formatter.parse(dateString);
                             System.out.println("date"+date);
                             //java.sql.Date publicationDate = (Date)book.getPublicationDate().getTime();
                             //System.out.println("Value of date is"+publicationDate);
                             System.out.println("After Date");
                             addBook.setDate(5,publicationDate);
                             addBook.setString(6,book.getCountry());
                             addBook.setString(7,book.getLanguage());
                             rs = addBook.executeQuery();
                             //con.commit();
                             rowCount = rowCount + rs.getRow();
                        return rowCount;
                   catch(SQLException se){
                        se.printStackTrace();
                   finally{
                        con.close();
                        System.out.println("After adding ");
              return 0;
         }

  • Trying to convert String to java.sql.Date

    I need to convert a String (in the format "yyyy-mm-dd") to java.sql.Date
    It was suggested I use the following,
    SimpleDateFormat formater = new SimpleDateFormat("yyyy-mm-dd");
    Date result = formater.parse(dbirth.getText());
    However, It seem to produce a java.util.Date
    Error: found java.util.Date
    Required : java.sql.Date
    Can anyone help?
    Thanks, Marika

    I need to convert a String (in the format
    "yyyy-mm-dd") to java.sql.Date
    It was suggested I use the following,
    SimpleDateFormat formater = new
    SimpleDateFormat("yyyy-mm-dd");
    Date result = formater.parse(dbirth.getText());
    However, It seem to produce a java.util.Date
    Error: found java.util.Date
    Required : java.sql.Date
    Can anyone help?
    Thanks, Marika SimpleDateFormat formater = new SimpleDateFormat("yyyy-mm-dd");
    java.util.Date parsedDate = formater.parse(dbirth.getText());
    java.sql.Date result = new java.sql.Date(parsedDate.getTime());

  • Convert a String to java.sql.Date Format

    Hi,
    I am having a String of containing date in the format 'dd/mm/yyyy' OR 'dd-MMM-YYYY' OR 'mm-dd-yyyy' format. I need to convert the string to java.sql.Date object so that I can perform a query the database for the date field. Can any one suggest me with the code please.
    Regards,
    Smitha

    import java.text.SimpleDateFormat;
    import java.text.ParseException;
    import java.util.Date;
    public class TestDateFormat
         public static void main(String args[])
              SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
              System.out.println(sdf.isLenient());
              try
                   Date d1 = sdf.parse("07-11-2001");
                   System.out.println(d1);
                   Date d2 = sdf.parse("07:11:2001");
                   System.out.println(d2);
              catch(ParseException e)
                   System.out.println("Error format, " + e);
    See class DateFormat and SimpleDateFormat for detail.

  • Convert String to java UTC date then to sql date

    Hi,
    I am trying to convert string (MM/dd/yyyy format) to UTC date time and store in the database.
    This is what I did:
    String dateAsString = "10/01/2007";
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    formatter.setLenient(false);
    java.util.date dateValue = formatter.parse(dateAsString, new ParsePosition(0));
    dateValue will be Sun Sep 30 20:00:00 EDT 2007 in UTC.
    Now I need to store this date and time to MS SQL database.
    I used the following code:
    java.sql.Date sqlDateValue = new java.sql.Date(parsedToDate.getTime());
    But this code give only the date, not time 2007-09-30
    Can anybody tell me how I can change this java date to sql date (or datetime?) so that I can get both date and time.
    Thanks,
    semaj

    semaj07 wrote:
    Hi,
    I am trying to convert string (MM/dd/yyyy format) to UTC date time and store in the database.
    This is what I did:
    String dateAsString = "10/01/2007";
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    formatter.setLenient(false);
    java.util.date dateValue = formatter.parse(dateAsString, new ParsePosition(0));
    dateValue will be Sun Sep 30 20:00:00 EDT 2007 in UTC.
    Now I need to store this date and time to MS SQL database.
    I used the following code:
    java.sql.Date sqlDateValue = new java.sql.Date(parsedToDate.getTime());
    But this code give only the date, not time 2007-09-30
    Can anybody tell me how I can change this java date to sql date (or datetime?) so that I can get both date and time.
    Thanks,
    semajTake a look at java.sql.Timestamp:
    http://java.sun.com/javase/6/docs/api/java/sql/Timestamp.html
    Edited by: hungyee98 on Oct 17, 2007 8:57 AM

  • Convert Calendar to Java.sql.Date

    I seached for a solution for converting a Calendar-object to a java.sql.date for inserting it into a MySQL DB (DateTime). I know this question is a FAQ. The solution I found is the following code:
    java.sql.Date sqlDate =  new java.sql.Date(cal.getTime().getTime() );When i do a print of the sqlDate to the console I get: sqlDate: 2005-06-27
    But when I look into de DB I get the following date: 27/05/1905
    I know that in Java the months are starting from 0-�11 and that the years counting is starting from 1900. But I assume that the solution is not to just add the correct month and year manually. because I get a correct console-output. If I do this I get a correct DB Date, but a wrong console-date.

    II dont know if you found an answer but I needed a similar solution so I wrote a test program.
    Let me know if this solves the problem for you.
    import java.util.*;
    import java.sql.*;
    public class dateTest{
    public static void main(String args[]){
    // Step by step
    // Calendar rightNow = Calendar.getInstance();
    // java.util.Date today = rightNow.getTime();
    // long theTime = today.getTime();
    // java.sql.Date sDate = new java.sql.Date(theTime);
    // In one line
    java.sql.Date sDate = new java.sql.Date(Calendar.getInstance().getTime().getTime());
    System.out.println("sDate is: "+sDate.toString());
    }

  • Converting String to java.sql.Time

    i have got a string like String time = "12:08 P.M.";
    I want to convert it to java.sql.Time .
    Please anyone suggest me the solution.

    CROSSPOST: http://forum.java.sun.com/thread.jspa?threadID=5162798&messageID=9621227
    A crosspost with only 2 postings. Is that a new record? Or does it just tie the record :-)

  • Convert a string to JAva.sql.date..

    I am having a string with the value as follows..
    String fval="03-10-2001"..
    I am using this value in a rs.updateDate method where I need to convert it to a different format as
    2001-10-03...can anybody give me the syntax..

    You should hold dates as Date instances. But if you want to convert between Strings and Dates then you should use a DateFormat:
    String originalDateString = "31-10-2001";
    // Convert the original string to a date
    DateFormat originalDateFormat = new SimpleDateFormat("dd-MM-yyyy");
    Date date = originalDateFormat.parse(originalDateString);
    // Get a representation of the date in the new format
    DateFormat newDateFormat = new SimpleDateFormat("yyyy-MM-dd");
    String newDateString = newDateFormat.format(date);(Excuse the quirky formatting that the Java code filter applies!)
    Hope this helps.

  • Converting String into Java code

    Hi everyone,
    I will describe the scenario I have. I have a GUI application. I want the user to write some Java code in a text box and plug that code during runtime. Is there a way in Java so that a string could be used as a Java code?
    You help is really appreciated.
    Thanks
    RG

    catch the string input
    output string (code) to file
    call javac on the file you made
    that's it, you have a class, and you can run it/load it

  • JTextfield input Date convert to java.sql.Date

    Hi. I have a textfield for users to input date in 'dd/mm/yyyy' format and I would like to format this input into java.sql.Date to be stored into a database. How should I go about doing that ?
    I did the following:
    SimpleDateFormat formatDate = new SimpleDateFormat("dd/mm/yyyy");
    java.util.Date invoiceDate = formatDate.parse(jTextField3.getText());
    java.sql.Date sqlDate = new java.sql.Date(invoiceDate.getTime());and when I input into jTextField3 the value '28/05/2008' , I found in my database '2008-01-28'. January and May is a few months off and is totally not what I wanted.

    Hi you did you code perfect, but you need to change the pattern for formatting the Date
    dd - date
    mm - minute
    yyyy - year
    here you are parsing month as minute, so the output may wrong..!
    If you need to format properly
    please use the below pattern
    {color:#0000ff}SimpleDateFormat formatDate = new SimpleDateFormat("dd/MM/yyyy");{color}

  • How do I create a Dynamic java.sql.Date ArrayList or Collection?

    I Have a MySQL table with a Datetime field with many values inserted.
    I want to know which is the Best way to capture all the Inserted DB values inside a Dynamic Array.
    I get errors that state that I should use Matching data-types, and plus I don't know how to create or fill a Dynamic Date ArrayList/Collection.
    Please Help, I need this urgently...

    package pruebadedates;
    import java.sql.*;
    * @author J?s?
    public class ClaseDeDates {
        /** Creates a new instance of ClaseDeDates */
         * @param args the command line arguments
        public static void main(String[] args) {
            java.sql.Date aDate[] = null;       
            Connection con = null;
            Statement stmt = null;
            ResultSet rs = null;
            try{
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                con = DriverManager.getConnection("jdbc:mysql://localhost/pruebafechas", "root", "picardias");
                    if(!con.isClosed()){
                    stmt = con.createStatement();
                    stmt.executeQuery ("SELECT dates FROM datestable");
                    rs = stmt.getResultSet();
                        while (rs.next())
                        aDate[] = rs.getDate("dates");
            catch(Exception e)
               System.out.println(e);
            //System.out.println(aDate);     
    }Hi, There is my code and the errors that I get are:
    found : java.sql.Date
    required: java.sql.Date[]
    aDate = rs.getDate("dates");
    Actually I have No idea as How to get a Result set into an ArrayList or Collection. Please tell me how to do this Dynamically. I have like 25 records in that Database table, but they will grow, so I would really appreciate to know the code to do this. I suspect my problem is in the bolded part of my code.
    Thank you very much Sir.

  • How to change a date value from "java.util.Date" to "java.sql.Date"?

    Hi all,
    How to change a date value from "java.util.Date" to "java.sql.Date"?
    I m still confusing what's the difference between them.....
    thanks
    Regards,
    Kin

    Thanks
    but my sql statement can only accept the format (yyyy-MM-dd)
    such as "select * from xx where somedate = '2004-12-31'
    but when i show it to screen, i want to show it as dd-MM-yyyy
    I m using the following to change the jave.util.Date to str and vice versa. But it cannot shows the dd-MM-yyyy. I tried to change the format from yyyy-MM-dd to dd-MM-yyyy, it shows the wrong date in my application.
         public String date2str(java.util.Date thisdate)     {
              if (thisdate != null)     {
                   java.sql.Date thissDate = new java.sql.Date(thisdate.getTime());
                   return date2str(thissDate);
              }     else     {
                   return "";
         public String date2str(java.sql.Date thisdate)     {
              if (thisdate != null)     {
                   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                   return sdf.format(thisdate);
              }     else     {
                   return "";
         public java.util.Date str2date(String thisdate)     {
              String dateFormat = "yyyy-MM-dd"; // = 1998-12-31
              java.util.Date returndate = null;
              if (thisdate != null)     {
                   SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);
                   try {
                        returndate = dateFormatter.parse(thisdate);
                   } catch (ParseException pe) {
                        System.out.println (pe.getMessage());
              return returndate;
         }

  • How to convert JAVA.SQL.DATE date in YYYY/MM/DD format into DD/MM/YYYY

    i am using informix database which accepts date value in the form of DATE format......
    the other part of my application takes date from the field in DD/MM/YYYY format...so i have to convert my java.sql.date in YYYY/MM/DD fromat into DD/MM/YYYY fromat of same type before inserting into db......
    but using parse method in SimpleDateFormat class can get the result only in java.util.date format...
    and also using format method can result only in string conversion........

    816399 wrote:
    i am using informix database which accepts date value in the form of DATE format......Huh?
    Maybe you mean Informix (fronted by JDBC) expects date values as java.sql.Date objects?
    the other part of my application takes date from the field in DD/MM/YYYY format...
    so i have to convert my java.sql.date in YYYY/MM/DD format into DD/MM/YYYY format of same type before inserting into db......I am not sure why you are talking about formats here.
    There is no formatting inherent in a java.util.Date object
    nor in a java.sql.Date object.
    but using parse method in SimpleDateFormat class can get the result only in java.util.date format...
    and also using format method can result only in string conversion........You can easily create a java.sql.Date object from a java.util.Date object.
    String s = "31/12/2010";
    java.util.Date ud = new java.text.SimpleDateFormat("dd/MM/yyyy").parse(s);
    java.sql.Date sd = new java.sql.Date(ud.getTime());
    ud = sd; // java.sql.Date extends java.util.Date so no conversion is needed

  • How to convert String date to java sql date

    I have an html form for entering the Date on retreving that value in a java servlet i get it as a string i want to convert that date to SQL date format so that i could use setDate() method of the java.sql.Date class to update the date value in the database.
    i used the following way but i need the code without using the deprecated ones.
    String delDate = (String)p_Request.getParameter("deleteDate");
    [b]java.util.Date utilDate = new java.util.Date(delDate);
    java.sql.Date deleteDate = new java.sql.Date(utilDate.getTime());
    custCode = (String)p_Request.getValue("custCode");
    thanx in advance.

    Check out the later posts in http://forum.java.sun.com/thread.jspa?threadID=647681&messageID=3814745#3814745

Maybe you are looking for

  • Why are my browsers (and app store) crashing?

    First, some context. I got my iMac last year around July. It worked well. Upgraded to Mountain Lion and everything seemed ok. Yes there were crashes here and there but they were few and far between. Around November, I noticed that things began to get

  • Lost my OS Cd for MAC Mini how can i get a replacement CD

    I have lost the Mac Mini Cd which came with the box , I need to re install my MAC OS, the Apple Phone support aint letttine me through , Is there anyone i can mail on Apple to get it done,

  • MOG missing songs from an album

    Hi guys, Veil Of Maya - Matriarch (2015) Missing a lot of songs! Can this be corrected please? Awesome band haha

  • APA Style Template in Pages for Mac?

    Does anyone know how to create an APA style Template in Pages for Mac?

  • 11gR2 Beta Test Programme

    In order to investigate using a Times 10 database with embedded PL/SQL business logic we are interested in joining the Times 10 11gR2 Beta Test programme. Can anyone point me in the right direction to join this programme please? An alerntaive to this