Convert a date in String format to a Date

Hi,
How can I convert a date in String format to a Date object?
I have tried:
import java.text.*;
import java.io.*;
import java.util.Date;
import java.util.Locale;
import java.sql.*;
public class casa {
public static Connection con = null;
public static Statement s = null;
public static String sql = null;
public static String mydate = "01.01.2001";
/** Creates a new instance of casa */
public casa() {
public static void main(String[] args) throws SQLException{
try {
DateFormat shortFormat = DateFormat.getDateInstance(DateFormat.SHORT);
Date date = shortFormat.parse(mydate);
//Open Database
con = getConnection();
s = con.createStatement();
sql = "select date1 from table1 where date1 <= '"+date+"'";
ResultSet rs = s.executeQuery(sql);
while(rs.next()){
String aba = rs.getString("datum");
System.out.println("New Datum = "+aba);
} catch (Exception ex ) {
ex.printStackTrace();
closeConnection(s, con);
//Connection
private static Connection getConnection() {
Connection con = null;
String user ="aouzi";
String passe ="aouzi";
String url = "jdbc:db2:EjbTest";
try {
//Datenbanktreiber laden
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
//Verbindung herstellen
con = DriverManager.getConnection(url,user,passe);
}catch(ClassNotFoundException e){
} catch(SQLException e){}
return con;
//close Connection
private static void closeConnection(Statement s, Connection con) {
try {
s.close();
} catch (SQLException e) {}
try {
con.close();
} catch (SQLException e) {}
I'm getting the following errors:
COM.ibm.db2.jdbc.DB2Exception: [IBM][CLI Driver][DB2/NT] SQL0180N
The syntax of the representation of a date/time of day value as character sequence is false. .SQLSTATE=22007

I'm pretty sure it won't understand what date.toString() returns. If you know what format the database understands, you do it like this:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy"); // e.g. 18-Apr-02
String datestring = sdf.parse(date);
and use that instead of date in your sql string. Some databases understands it if you do
"to_date('18-Apr-02')"
so you could include that in your sql string as well..
You could also try to make it a java.sql.Date and hope your jdbc driver knows how to convert it to a string that the database understands if you don't know the format:
con = getConnection();
PreparedStatement ps = con.prepareStatement("select date1 from table1 where date1 <= ?");
ps.setDate(new java.sql.Date(date.getTime()));
ResultSet rs = s.executeQuery(sql);

Similar Messages

  • How to convert BLOB data into string format.

    Hi,
    I have problem while converting blob data into string format.
    for example,
    Select dbms_lob.substr(c.shape.Get_wkb(),4000,1) from geotable c
    will get me the first 4000 byte of BLOB .
    When i using SQL as i did above,the max length is 4000, but i can get 32K using plsql as below:
    declare
    my_var CLOB;
    BEGIN
    for x in (Select X from T)
    loop
    my_var:=dbms_lob.substr(x.X,32767,1)
    end loop
    return my_var;
    I comfortably convert 32k BLOB field to string.
    My problem is how to convert blob to varchar having size more than 32K.
    Please help me to resolve this,
    Thanx in advance for the support,
    Nilesh

    Nilesh,
    . . . .The result of get_wkb() will not be human readable (all values are encoded into some binary format).
    SELECT utl_raw.cast_to_varchar2(tbl.geometry.get_wkt()) from FeatureTable tbl;
    -- resulting string:
        ☺AW(⌂özßHAA
    Å\(÷. . . .You may also want to have a look at { dbms_lob | http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_lob.htm#i1015792 } "The DBMS_LOB package provides subprograms to operate on BLOBs, CLOBs, NCLOBs, BFILEs, and temporary LOBs."
    Regards,
    Noel

  • Convert HH:mm:ss String format.

    Hi,
    I have a formula in webI to display Milliseconds to HH:mm:ss and is in String format.
    Is there a way to convert to date or number format?.
    Also, how to calculate average of Max and Min time?.
    Thanks,
    Jothi

    Hi Jyothi,
    To take a average time do following-
    1) Convert Min Time and Max Time into Seconds.
    MaxSec=ToNumber(Substr([MaxTime];1;2))*60*60+ToNumber(Substr([MaxTime];4;2))*60+ToNumber(Substr([MaxTime];7;2))
    MinSec=ToNumber(Substr([MinTime];1;2))*60*60+ToNumber(Substr([MinTime];4;2))*60+ToNumber(Substr([MinTime];7;2))
    2) calculate approximate Avg seconds-
    AvgSec=([MaxSec]+[MinSec])/2
    3) Convert AvgSec in to hh:mm:ss.
    AvgTime=Floor([AvgSec]/3600 )+":"+Floor(Mod([AvgSec];3600)/60)+":"+Mod(Mod([AvgSec];3600);60)
    Hope this help.
    Thanks,
    Anuj

  • Date Problem-adding 30days to the date in string format.

    hi i have an Date in the form of String "yyyy-mm-dd",i have to add 30 days to that date and compare it with to days date,i try to convert the string in to date format using SimpleDateFormat,but i could not understand how to add 30 days to that.pl it's an urgent problem,any help would be appreciated.
    Regards.

    to compare the date to todays date,
    Calendar todaysDate = Calendar.getInstance();
    todaysDate.after(cal2);
    todaysDate.before(cal2);
    Depending on which way you want to know.
    To get the String Format I would suggest something like :
    String dateInString = "" + cal2.get(Calendar.YEAR) + "-" + cal2.get(Calendar.MONTH) + "-" + cal2.get(Calendar.DATE);
    Be careful though as this may give a format YYYY-M-D if the month or date is a single digit, so you may have to test string.length and then have "0"+cal2.get(Calendar.MONTH) /cal2.get(Calendar.DATE)
    Hope this is of some help.

  • How to read date as string (format dd-mm-yyyy) and store it as Date object

    Hi. I would like to read from keyboard String with a date and put this value to Date object. How can i do this???
    Thanks

    Check out java.text.SimpleDateFormat.
    Basically
    String dateString = readUserInput(); // get the string
    SimpleDateFormat myFormat = new SimpleDateFormat("dd-MM-yyyy");
    Date myDate = myFormat.parse(dateString);

  • Retain data in String Display untill new data is delivered in RS-232

    I am using Labview 8.6 on Windows XP OS and acquiring signal from RS-232 through COM1 port to which I have connected non NI instrument. My instrument sends data for flash of second and it displayed into String Indicator for flash of second. How to hold this data untill I get new data from instrument. I have tried to select "re-initialise to default value" and "make current value default" but none of them getting selected. I want data to be retained untill new data comes. I have enclosed VI as well as Picture file. Pl advice. 
    Attachments:
    HPLC Flow Meter 3.vi ‏32 KB
    HPLC FLow 3.JPG ‏123 KB

    -Looks you are sending or running the while loop every 5ms, are you sure you want this fast? This is the reason the data comes in flash(i think 5ms)
    -I use shift register to store something from previous iterations generally.
    -You need to keep case structure to check when new data comes and when it does, replace the value in that string.
    -else pass previous value to string.
    Thanks
    uday,
    Please Mark the solution as accepted if your problem is solved and help author by clicking on kudoes
    Certified LabVIEW Associate Developer (CLAD) Using LV13

  • How can i convert if the date in string format

    String lFstr = (String) pReq.getParameter("FND");
    String lTstr = (String) pReq.getParameter("TND");
    String lLstr = (String) pReq.getParameter("LWD");
    System.out.println(lFstr + " " + lTstr + " " + lLstr);
    //DateFormat ds = DateFormat.getDateInstance();
    DateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
    Date lFdate = null;
    Date lTdate = null;
    Date lLdate = null;
    try {
    lFdate = dateFormatter.parse(lFstr);
    lTdate = dateFormatter.parse(lTstr);
    lLdate = dateFormatter.parse(lLstr);
    } catch (Exception e) {
    System.out.println(lFdate+" "+lTdate+" "+lLdate);
    i am getting the values from request parameters at that time it is giving values.
    after convertion of string to date it is giving the null value what is wrong in this code

    It might have thrown an exception. Try printing the stack trace in the catch block.

  • Converting library to new file format without losing data

    I want to convert my library to a standardized file format, but I don't want to lose the data (play counts, playlists, etc.) that are associated with the current files. Is there any way to convert my AAC files (what my library is currently using) to MP3 files (the format I want them to be) while retaining my play counts, etc?

    It seems the only problem I'm really having is getting voice memos on my iPhone to transfer to the new iMac / iTunes. I've fully synced the device but the voice memos do not appear in the music folder after syncing, even though I've checked 'Include voice memos' on the 'Sync Music' tab of the iPhone device. The are on the iPhone and I can play them still.
    In fact, now the 'Voice Memos' app that comes native with iPhone will no longer record after syncing to the new iMac... I'm totally confused by what's happening!

  • Convert date in sql format

    how to convert a date in string format to sql date format?
    thanx in advance

    Use java.text.SimpleDateFormat to parse the String into a java.util.Date.
    Create a java.sql.Date from the java.util.Date.
    Use a PreparedStatement and its setDate() method to set the date in the SQL. The JDBC driver will take care of putting that java.sql.Date object into the correct format for your DB.

  • Convert the date of string to datetime format 'MM/dd/yyyy' when the system date format is 'dd/MM/yyyy'.

    I need convert the date of string format 'MM/dd/yyyy' to datetime format 'MM/dd/yyyy' when the system date format is 'dd/MM/yyyy'.Since
    I need to search values based on date where my database datetime  is 'MM/dd/yyyy' format.

    In my opinion you should re-consider the assumption that the date picker returns a string. Maybe it is able to return a
    DateTime object directly instead of string. Then you will pass this value as a parameter of SQL query. This should work regardless of computer configuration.
    Otherwise, follow the previous string-based approaches.

  • How to Get Blob data(In String Form) using OCCI

    Hello frnds,
    I am new to OCCI,so i hvnt that much of master in that side.
    I have one problem while handling BLOb data.
    How to convert binary form of SDO_GEOMETRY data into string format. I am able to convert data by using PLSQL block,but its take so much time to execute.So performance is the main issue.So if there is any API in OCCI which convert directly blob data into string format.
    Thanx in advance for your support,
    Nilesh.

    Have you tried reading "http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28390/lobs.htm#BABDEGJD" ? This explains how you can read from BLOBs into a C vector (or C++ vector of chars).

  • String.format()   error (works in a class file , not in jsp)

    Hello all,
    I am using Java 5 and am trying to use the String.format() method in a jsp but am getting the following error:
    HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 5 in the jsp file: /ajax.jsp
    Generated servlet error:
    C:\Documents and Settings\gforte\.netbeans\5.0beta2\jakarta-tomcat-5.5.9_base\work\Catalina\localhost\agi\org\apache\jsp\ajax_jsp.java:50: cannot find symbol
    symbol : method format(java.lang.String,java.util.Date,java.util.Date)
    location: class java.lang.String
    String dateString = String.format("%tb%td",date,date);
    ^
    1 error
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:84)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:328)
         org.apache.jasper.compiler.AntCompiler.generateClass(AntCompiler.java:246)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:288)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:267)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:255)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:556)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:293)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362)
    note The full stack trace of the root cause is available in the Apache Tomcat/5.5.9 logs.
    Apache Tomcat/5.5.9
    The code I am using is working fine in a class file but wont work in my jsp.
    <%@page import="java.util.*,java.lang.String"%>        
    Date date = new Date();
    String dateString = String.format("%tb%td",date,date);
    System.out.println(dateString);Any ideas?

    I get excactly the same problem.
    If compile the the JSP in Netbeans it works fine, however when Tomcat attempts to compile it into a servlet at runtime, I get the same error as described.
    This is the line in JSP that fails:
    <code>Some more text <%= String.format("%s","Bizarre") %> </code>However this one works OK:
    <code>Some more text <%= "Bizarre".substring(3) %> </code>Its almost as if Tomcat is compiling under JDK 1.4.2 or something but I don't have any other JDK or JRE installed; only 1.5.
    I suspect it may be a Tomcat setting that's causing a 1.4 code compliance.
    In Netbeans, if I go to the project properties -> Sources, at the bottom is the "Source Level" drop down list. If I change this to 1.4 and clean and build the whole project I get the same error when the jsp (or any class with this construct) is compiled by NetBeans.
    Note: I am using the Netbeans 5.0 and Tomcat and 5.5.9 co-bundle which I downloded from the Sun website.
    Can anyone help?
    Heres the splurge from the browser output:
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 55 in the jsp file: /login.jsp
    Generated servlet error:
    C:\Documents and Settings\Peter\.netbeans\5.0\jakarta-tomcat-5.5.9_base\work\Catalina\localhost\SuperStruts\org\apache\jsp\login_jsp.java:105: cannot find symbol
    symbol  : method format(java.lang.String,java.lang.String)
    location: class java.lang.String
          out.print( String.format("%s","Bizarre") );
                           ^
    1 error
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:84)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:328)
         org.apache.jasper.compiler.AntCompiler.generateClass(AntCompiler.java:246)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:288)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:267)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:255)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:556)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:293)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362)
    Note also that when I run this JSP page:
    <%@page import="java.util.*"%>
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%
            Properties p = System.getProperties();
            Enumeration keys = p.keys();
            Object key;
            while (keys.hasMoreElements()) {
                key = keys.nextElement();
                out.println("key: " + key + " - " + p.getProperty((String)key) + "<br/>");
    %>     ... I get this browser output:
    key: java.runtime.name - Java(TM) 2 Runtime Environment, Standard Edition
    key: sun.boot.library.path - C:\Program Files\Java\jdk1.5.0_06\jre\bin
    key: java.vm.version - 1.5.0_06-b05
    key: shared.loader - ${catalina.base}/shared/classes,${catalina.base}/shared/lib/*.jar
    key: java.vm.vendor - Sun Microsystems Inc.
    key: java.vendor.url - http://java.sun.com/
    key: path.separator - ;
    key: tomcat.util.buf.StringCache.byte.enabled - true
    key: java.vm.name - Java HotSpot(TM) Client VM
    key: file.encoding.pkg - sun.io
    key: user.country - GB
    key: sun.os.patch.level - Service Pack 2
    key: java.vm.specification.name - Java Virtual Machine Specification
    key: user.dir - C:\Program Files\netbeans-5.0\enterprise2\jakarta-tomcat-5.5.9\bin
    key: java.runtime.version - 1.5.0_06-b05
    key: java.awt.graphicsenv - sun.awt.Win32GraphicsEnvironment
    key: java.endorsed.dirs -
    key: os.arch - x86
    key: java.io.tmpdir - C:\Documents and Settings\Peter\.netbeans\5.0\jakarta-tomcat-5.5.9_base\temp
    key: line.separator -
    key: java.vm.specification.vendor - Sun Microsystems Inc.
    key: java.naming.factory.url.pkgs - org.apache.naming
    key: java.util.logging.manager - org.apache.juli.ClassLoaderLogManager
    key: user.variant -
    key: os.name - Windows XP
    key: sun.jnu.encoding - Cp1252
    key: java.library.path - C:\Program Files\Java\jdk1.5.0_06\bin;.;C:\WINDOWS\system32;C:\WINDOWS;C:\oracle\product\10.2.0\db_2\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\ATI Technologies\ATI.ACE\;C:\Program Files\MySQL\MySQL Server 5.0\bin;C:\Program Files\Common Files\GTK\2.0\bin;C:\Program Files\CVSNT\
    key: java.specification.name - Java Platform API Specification
    key: java.class.version - 49.0
    key: sun.management.compiler - HotSpot Client Compiler
    key: os.version - 5.1
    key: user.home - C:\Documents and Settings\Peter
    key: catalina.useNaming - true
    key: user.timezone - Europe/London
    key: java.awt.printerjob - sun.awt.windows.WPrinterJob
    key: file.encoding - Cp1252
    key: java.specification.version - 1.5
    key: catalina.home - C:\Program Files\netbeans-5.0\enterprise2\jakarta-tomcat-5.5.9
    key: java.class.path - C:\Program Files\Java\jdk1.5.0_06\lib\tools.jar;C:\Program Files\netbeans-5.0\enterprise2\jakarta-tomcat-5.5.9\bin\bootstrap.jar
    key: user.name - Peter
    key: java.naming.factory.initial - org.apache.naming.java.javaURLContextFactory
    key: package.definition - sun.,java.,org.apache.catalina.,org.apache.coyote.,org.apache.tomcat.,org.apache.jasper.
    key: java.vm.specification.version - 1.0
    key: java.home - C:\Program Files\Java\jdk1.5.0_06\jre
    key: sun.arch.data.model - 32
    key: user.language - en
    key: java.specification.vendor - Sun Microsystems Inc.
    key: awt.toolkit - sun.awt.windows.WToolkit
    key: java.vm.info - mixed mode
    key: java.version - 1.5.0_06
    key: java.ext.dirs - C:\Program Files\Java\jdk1.5.0_06\jre\lib\ext
    key: sun.boot.class.path - C:\Program Files\Java\jdk1.5.0_06\jre\lib\rt.jar;C:\Program Files\Java\jdk1.5.0_06\jre\lib\i18n.jar;C:\Program Files\Java\jdk1.5.0_06\jre\lib\sunrsasign.jar;C:\Program Files\Java\jdk1.5.0_06\jre\lib\jsse.jar;C:\Program Files\Java\jdk1.5.0_06\jre\lib\jce.jar;C:\Program Files\Java\jdk1.5.0_06\jre\lib\charsets.jar;C:\Program Files\Java\jdk1.5.0_06\jre\classes
    key: server.loader - ${catalina.home}/server/classes,${catalina.home}/server/lib/*.jar
    key: java.vendor - Sun Microsystems Inc.
    key: catalina.base - C:\Documents and Settings\Peter\.netbeans\5.0\jakarta-tomcat-5.5.9_base
    key: file.separator - \
    key: java.vendor.url.bug - http://java.sun.com/cgi-bin/bugreport.cgi
    key: common.loader - ${catalina.home}/common/classes,${catalina.home}/common/i18n/*.jar,${catalina.home}/common/lib/*.jar
    key: sun.io.unicode.encoding - UnicodeLittle
    key: sun.cpu.endian - little
    key: package.access - sun.,org.apache.catalina.,org.apache.coyote.,org.apache.tomcat.,org.apache.jasper.,sun.beans.
    key: sun.desktop - windows
    key: sun.cpu.isalist - demonstrating (I think) that the correct JDK and JDK are in use by Tomcat.

  • Specify the output date to be of a Specified date format.

         DateFormat  formatter = new SimpleDateFormat("MM/dd/yyyy");
         String dateString = "12/12/2006";
         Date dateStringInDateFormat = formatter.parse(dateString);
         System.err.println("the date"+dateStringInDateFormat);
         String str1 = formatter.format(dateStringInDateFormat);
         System.err.println("the date in string format"+str1);
         DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
         df.setLenient(false);
         Date stick = df.parse(str1);
          System.err.println("The final date to be passed"+stick);The output that i get on screen:
    the date Tue Dec 12 00:00:00 GMT 2006
    the date in String format 12/12/2006
    The final date to be passed Tue Dec 12 00:00:00 GMT 2006
    I want the final date to be passed i.e, Date stick to be 12/12/2006
    Can anyone helpme in this issue

    DateFormats do not change what a Date object contains or how it is displayed. They are only used to format the output when you use them with format(Date). The Date object itself is unchanged and you cannot change it.
    So whereever you want to display a date in your particular format you will need to use your DateFormat.

  • Date and Amount format in BDC

    Hi friends,
       I am facing problem with date and currency format while uploading data through BDC.
       Plz. tell me how to handle the problems related to Date and amount format.
       Thanks in Advance

    Dear Punit,
    This is a common problem, when carrying out BDC.
    For example, while recording you met with the 2 fields --> MSEG-DMBTR (Curr) and MSEG-MENGE(Quantity).
    Go to SE11 --> MSEG --> Search for DMBTR --> Double click on the Data Element i.e. DMBTR --> Double Click on the domain WERTZ --> You can see under the block Output Characteristics : Output Length = 16.
    While declaring the TYPES Structure, make it CHAR(16).
    Similarly for MENGE --> Data Element : MENGE_D --> Domain : MENGE13 --> Output Length = 17.
    Make it CHAR(17).
    For Date field ---> CHAR(10).
    Consider this technique as the Rule-of-Thumb while doing BDC.
    Regards,
    Abir
    Don't forget to award points *

  • Convert string (in a Julian Date format) to a date in CR XI Release 2

    How do you convert a string field  entered in a database as a Julian date " 10109 , 09008. ,,," to
    print on a report as  date?
    09008 would be 01/08/09
    10109                 04/19/10

    A small correction to Brian's formula:
    NumberVar myYear;
    NumberVar myDays;
    myYear := ToNumber( {table.JULIAN} [1 to 2]);
    myDays := TONUMBER({table.JULIAN} [3 to 5]);
    (Date (myYear, 1, 1) + myDays) - 1;
    The result for '09008' will be 01/08/9, by adding ToText, you can get the result in the desired format of 01/08/09.
    totext((Date (myYear, 1, 1) + myDays) - 1, "MM/dd/yy");
    Here is an alternate solution without having to create variables:
    totext(dateserial(tonumber(X[1 to 2]),1,tonumber(X[3 to 5])),"MM/dd/yy");
    where X is the julian date in string.
    Edited by: Sanjay Kodidine on Apr 20, 2010 8:25 AM

Maybe you are looking for