How to conver string date to sql date

Hi,
i have a html form which will populate the date in the text field using popup window in the mm\dd\yy format .
In the servlet i first retrieve the value as string object and need to store that one the database. using setDate method of prepared statement
The date should be of type sql date only.
so my question is how to convert the string representation of the date to sql date.
Thanx in advance

use java.text.DateFormat and java.text.SimpleDateFormat.
%

Similar Messages

  • 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;
         }

  • 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 util.Date to sql.Date with time being displayed!

    Hi all,
    I want to convert util.Date to sql.Date for passing the same to Database. (i donot want to use Timstamp, for some reasons)
    java.sql.Date sqldate =
    new java.sql.Date(new java.util.Date().getTime());
    This simple code truncates the Time component and the result will be only Date. But my requirement is for Data and Time, both.
    Request anyone to suggest how to go abt this problem.
    Thanx.

    You can use the class java.text.DateFormat (java.text.SimpleDateFormat) for displaying. For example like this.
    java.sql.Date sqldate = new java.sql.Date(new java.util.Date().getTime());
    java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyy.MM.dd 'at' HH:mm:ss z");
    String str = formatter.format(sqldate);
    System.out.println(str);

  • Help converting between Java Dates and SQL Dates

    Hey all,
    I'm working on a JSP to allow a user to enter information about news articles into a mySQL database. I'm using text fields for most of the data, and most of it is transferred correctly when the user hits "Submit." However, I am having a problem with the date field of the mySQL database. Basically I'm trying to retrieve the current date from the JSP page, and then insert this into the date field of the appropriate table when the user hits submit. The problem is that I can't typecast a java.util.Date or even a java.util.Calendar to a java.sql.Date object. I've tried lots of approaches, including creating a new instance of java.util.Calendar, getting all its fields and concatenating them onto the date variable, but this doesn't work.
    Anyone know how I could easily convert between java.util.Date or java.util.Calendar and java.sql.Date?
    Thanks!

    Thanks for the help!
    I can correctly display the current date on the page in java.sql.Date format now, but it's still not being inserted into the database correctly. The specific code is as follows:
    java.util.Date dt = new java.util.Date();
    java.sql.Date sqlDate = new java.sql.Date(dt.getTime());
    (As you wrote)
    Then (after connecting to the database etc.):
    PreparedStatement pstmt = con.prepareStatement("INSERT INTO NEWS(NEWSDATE,DAYOFWEEK,AUTHOR,HEADLINE,CLIP,PUBLICATION,LINK,NEWSLOCATION,DATECREATED,DATEMODIFIED,CATEGORY,KEYWORDS,PHOTOURL,PHOTOGRAPHER,AUDIOURL) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
    pstmt.clearParameters();
    pstmt.setString(1,date);
    pstmt.setString(2,dayofweek);
    pstmt.setString(3,author);
    pstmt.setString(4,headline);
    pstmt.setString(5,clip);
    pstmt.setString(6,publication);
    pstmt.setString(7,link);
    pstmt.setString(8,newslocation);
    pstmt.setDate(9,sqlDate);
    pstmt.setString(10,datemodified);
    pstmt.setString(11,category);
    pstmt.setString(12,keywords);
    pstmt.setString(13,photoURL);
    pstmt.setString(14,photographer);
    pstmt.setString(15,audioURL);
    int i = pstmt.executeUpdate();
    pstmt.close();
    All the other fields are retrieved with request.getParameter from text fields. Any idea why the DATECREATED field is being updated to all 0's but the others work fine?
    Thanks again.

  • Date difference when converting Calendar date to sql date

    I am trying to convert a Calendar date to sql date. The only problem in the conversion is sql date adds 1 month to the original date. Due to this my query results show different data than what it is suppossed to show.
    Here is my code
    Calendar startDate = Calendar.getInstance();
    startDate.set(2006, 10, 01, 00, 00); // 1-Oct-2006
    return (new java.sql.Date(date.getTimeInMillis()));
    on the last statement it adds a month to original date. So the final date i get is 1-Nov-2006.
    Any solution to this problem?
    Thanks
    Sameer

    Thanks everyone for quick response.
    I have read javadocs many times but that does not
    change the fact that Calendar and Sql date
    interpretation is different.No, it isn't. You are setting the moth to november when you set the month to 10, and november is what java.sql.Date is showing. So where is the difference? You are doing it wrong and that is why you get the wrong month.
    How the f do you think that the calender should know that you want october when you set it to november?
    My application is deployed through web service and
    the clients may access it through any programming
    langague (java, php, ec). Even I am testing it
    through java and php. Still doesn't matter. You need to subtract the month by one if you want to let your user use 1 for january.
    While testing it through java month is different but
    through php its correct.Read the docs.
    Can smoeone please give me the best possibel solution
    to this?see above

  • 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;

  • Converting String to Date (java.sql.date)

    Hi,
    Kindly let me know how I can convert a string like
    "20061102" (YYYYMMDD) to a Date type (java.sql.date) in web Dynpro.
    Requirement is to set a DateType context Attribute with
    the value contained in the String ("20061102" ).
    Awaiting your kind responses..
    Regards,
    Mahesh

    SimpleDateFormat yyyyMMdd_parser = new SimpleDateFormat(
                   "yyyyMMdd");
    java.util.Date date=yyyyMMdd_parser.parse("20061102");
    java.sql.Date slqDate=new java.sql.Date(date.getTime());

  • 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 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.

  • 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.

  • Using relational data from SQL data source in Planning and Essbase

    Hi,
    How do I take sample data from a SQL data source and bring it into a Hyperion Planning application? I understand that when creating Planning applications, a link between a relational data source and Essbase must be established, because the relational database holds the metadata while the database outline is stored with Essbase. However, all I am currently able to do is load the data into Planning applicaitons via EAS, where I right-click on the Application database, hit load data, and select from either a .txt file or an excel file. Do I need Oracle Data Integrator? Any help or insight would be greatly appreciated, as well as corrections to any incorrect assumptions I may have made in this post. Thank you.

    When you import your file (Excel or text), you're importing it using a Load Rule in EAS. To load from SQL, you simply create a SQL load rule. You'll load data the exact same way (via EAS), but with a different type of load rule. The load rule will contain the SQL that queries the database. You can preview your data in the load rule the same way you would with a file.
    If your SQL is very complex, I'd recommend creating a view and loading from that view. But otherwise it's pretty straight-forward.
    The only catch is that you need to configure a database connection (to your relational database) on the Essbase server. The Essbase DBA guide will show you how to do this.
    You COULD use ODI, but I tend to only use it for loading metadata.
    Hope this helps,
    - Jake

  • Conversion of JDBC date to SQL date!!

    I've a date format of "Sun Dec 03 01:18:11 IST 2006" (JDBC format)
    and want to convert in into "2006/12/03 01:18:11:00" (SQL format).
    I've tried with SimpleDateFormat, but it didn't work. It is not accepting that value or format.
    Could anyone help me out!!!!

    JDBC format? SQL format? Huh?
    You need to be working with java.sql.Date and PreparedStatements to properly escape the Date in the database.
    As for the SimpleDateFormat, what does "not work" look like?
    package cruft;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.text.ParseException;
    import java.util.Date;
    * DateFormatTest
    * @author md87020
    * @since Dec 20, 2006
    public class DateFormatTest
       public static void main(String[] args)
          DateFormat formatter = new SimpleDateFormat("E MMM dd hh:mm:ss z yyyy");
          for (int i = 0; i < args.length; ++i)
             try
                Date date = null;
                date = formatter.parse(args);
    System.out.println(date);
    catch (ParseException e)
    System.err.println("i: " + i + " value: " + args[i]);
    e.printStackTrace();
    This program appears to be doing some Locale conversions for me, and I don't have time to sort it out.
    But the idea is that you should be sending java.sql.Date to the database. Let the JDBC driver handle any SQL conversions for you with PreparedStatements.

  • Retrieve Data using SQL Data Reader

    Hello Team, I am working on a program where we have to read the data from sql database for specific barcode. Please have a look at the code below.
    If SqlConnection.State = ConnectionState.Closed Then
    SqlConnection.Open()
    End If
    Try
    Dim SQLCommand As New SqlClient.SqlCommand("SELECT * FROM tblProducts WHERE Barcode= @Barcode", SqlConnection)
    SQLCommand.Parameters.AddWithValue("@Barcode", txtPurchaseBarcode.Text)
    frmNoBarcode.lblBarcode.Text = txtPurchaseBarcode.Text
    Dim SQLReader As SqlClient.SqlDataReader
    SQLReader = SQLCommand.ExecuteReader
    If SQLReader.Read Then ' Barcode Exist
    ' Load Product Name
    lblFetchProduct.Text = SQLReader.Item("ItemName").ToString
    SQLReader.Close()
    End If
    Catch ex As Exception
    End Try
    If SqlConnection.State = ConnectionState.Open Then
    SqlConnection.Close()
    End If
    So It display the records, I just want that, in some case, if the program is unable to search for the barcode,  then program should give me a message that the Item does not exist and Exit Sub the application. Can somebody help me up ?

    Sir, can you please help me by giving me a code sample so I can understand in a better way, thanks
    If you are referring to me, the way I would write the whole code: (just a suggestion...)
    Private Function GetItemNameFromTblProductsByBarcode(ByVal Barcode As String) As String
    If SqlConnection.State = ConnectionState.Closed Then
    SqlConnection.Open()
    End If
    Try
    Dim SQLCommand As New SqlClient.SqlCommand("SELECT ItemName FROM tblProducts WHERE Barcode= @Barcode", SqlConnection)
    Dim Value As Object
    SQLCommand.Parameters.AddWithValue("@Barcode", Barcode)
    Value = SQLCommand.ExecuteScalar
    Return If(Value Is Nothing, Nothing, Value.ToString)
    Finally
    SqlConnection.Close()
    End Try
    End Function
    '' Call:
    Dim Itemname As String
    Itemname = GetItemNameFromTblProductsByBarcode(txtPurchaseBarcode.Text)
    If Itemname Is Nothing Then
    MessageBox.Show( _
    "The item with the barcode " & txtPurchaseBarcode.Text & " does not exist.", "", _
    MessageBoxButtons.OK, MessageBoxIcon.Information)
    Else
    lblFetchProduct.Text = Itemname
    frmNoBarcode.lblBarcode.Text = Itemname
    End If
    I do not know whe meaning of lblFetchProduct and frmNoBarcode.lblBarcode, so I just set them both in case the barcode has been found.
    Armin

  • SQL Interface - Error in Loading the data from SQL data source

    Hello,
    We have been using SQl data source for loading the dimensions and the data for so many years. Even using Essbase 11.1.1.0, it's been quite a while (more than one year). For the past few days,we are getting the below error when trying to load the data.
    [Mon Jan 10 11:02:56 2011]Local/{App Name}/{DB Name}/{User Id}/Info(1021013)
    ODBC Layer Error: [S1000] ==> [[DataDirect][ODBC DB2 Wire Protocol driver][UDB DB2 for Windows, UNIX, and Linux]CURSOR IDENTIFIED IN FETCH OR CLOSE STATEMENT
    IS NOT OPEN (DIAG INFO: ).]
    [Mon Jan 10 11:02:56 2011]Local/{App Name}/{DB Name}/{User Id}/Info(1021014)
    ODBC Layer Error: Native Error code [4294966795]
    [Mon Jan 10 11:02:56 2011]Local/{App Name}/{DB Name}/{User Id}/Error(1021001)
    Failed to Establish Connection With SQL Database Server. See log for more information
    [Mon Jan 10 11:02:56 2011]Local/{App Name}/{DB Name}/{User Id}/Error(1003050)
    Data Load Transaction Aborted With Error [7]
    [Mon Jan 10 11:02:56 2011]Local/{App Name}///Info(1013214)
    Clear Active on User [Olapadm] Instance [1]
    Interestingly, after the job fails thru our batch scheduler environment, when I run the same script that's being used in the batch scheduler, the job completes successfully.
    Also, this is first time, I saw this kind of error message.
    Appreciate any help or any suggestions to find a resolution. Thanks,

    Hii Priya,
    The reasons may be the file is open, the format/flatfile structure is not correct, the mapping/transfer structure may not be correct, presence of invalid characters/data inconsistency in the file, etc.
    Check if the flatfile in .CSV format.
    You have to save it in .CSV format for the flatfile loading to work.
    Also check the connection issues between source system and BW or sometimes may be due to inactive update rules.
    Refer
    error 1
    Find out the actual reason and let us know.
    Hope this helps.
    Regards,
    Raghu.

Maybe you are looking for