Convert string to mysql datetime in java

Hi,
Can somebody suggest me how to convert a date string in this format - Mon Aug 10 16:36:00 CDT 2009 to a MySql DateTime in Java?
This date is the result of Apache POI. Below is my code:
if(HSSFDateUtil.isCellDateFormatted(hssfCell)) {
     cellData = HSSFDateUtil.getJavaDate(hssfCell.getNumericCellValue()).toString();
     break;
I want to insert cellData into MySql DateTime field.
Thanks.

First I would use a SimpleDateFormat object to parse that into a java.util.Date object.
Then I would create a java.sql.Timestamp object from that and insert it into a PreparedStatement which updates the appropriate column in your MySQL table. Note that using a PreparedStatement removes all the uncertainty of creating something in a "MySQL" format as it just tells the JDBC driver to deal with those details.

Similar Messages

  • How i convert string(dd/mm/yyyy) to java.util.Date object

    <%
       try{
             String date="1/8/2000";
             SimpleDateFormat ts= new SimpleDateFormat("dd-MMM-yyyy");
             Date  sqlToday = new java.sql.Date(ts.parse(date).getTime());
            out.println("I am Here");
             out.println("Date:"+sqlToday);
            out.println("After Date:");
             catch(ParseException e){
                  e.printStackTrace();
      %>It is the code and i cann't get any result.
    i am very new to JSTL and netbeans pls help me
    Thanks in Advance

    Write your format string to match the user input. ie yyyy-MM-dd (if that is what the user types in). MMM means month in short words - ie Jan, Feb, Mar etc
    Once you parse it into a date, and get a java.sql.Date, you should use a prepared statement and the setDate() method.
    Try
    dd/MM

  • 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

  • Converting string(which is an xml from the java side) to xml in flex

    Hi,
       I have an xml from the java side which i send as string over amf. I need to convert this to xmllist or xml and bind it to a tree. Could some one help me in doing this. My label field needs to be displayName
    this is my xml that comes as string to the flex side
    <Menu>
      <MenuItem>
        <id>1</id>
        <displayName>Add</displayName>
        <menuList>
          <MenuItem>
            <id>3</id>
            <displayName>Form1</displayName>
            <menuList/>
          </MenuItem>
          <MenuItem>
            <id>4</id>
            <displayName>Form2</displayName>
            <menuList/>
          </MenuItem>
        </menuList>
      </MenuItem>
      <MenuItem>
        <id>2</id>
        <displayName>Delete</displayName>
        <menuList>
          <MenuItem>
            <id>5</id>
            <displayName>Form1</displayName>
            <menuList/>
          </MenuItem>
          <MenuItem>
            <id>6</id>
            <displayName>Form2</displayName>
            <menuList/>
          </MenuItem>
        </menuList>
      </MenuItem>
    </Menu>

    Well, for Binding you will probably need to further convert to XMLListCollection or ArrayCollection.
    Not sure.
    However, that is the way to convert String to XML.

  • Converting Oracle XML Query Result in Java String by using XSU

    Hi,
    I have a problem by converting Oracle XML Query Result in Java
    String by using XSU. I use XSU for Java.
    For example:
    String datum=new OracleXMLQuery(conn,"Select max(ps.datum) from
    preise ps where match='"+args[0]+"'");
    String datum1=datum;
    I become the following error:
    Prototyp.java:47: Incompatible type for declaration. Can't
    convert oracle.xml.sql.query.OracleXMLQuery to java.lang.String.
    Can somebody tell me a method() for converting to solve my
    problem??????
    Thanks

    Hmmm.. Pretty basic just look at the example:
    OracleXMLQuery qry = new OracleXMLQuery(conn,"Select max(ps.datum) from preise ps where match='"+args[0]+"'");
    String xmlString = qry.getXMLString();
    Hi,
    I have a problem by converting Oracle XML Query Result in Java
    String by using XSU. I use XSU for Java.
    For example:
    String datum=new OracleXMLQuery(conn,"Select max(ps.datum) from
    preise ps where match='"+args[0]+"'");
    String datum1=datum;
    I become the following error:
    Prototyp.java:47: Incompatible type for declaration. Can't
    convert oracle.xml.sql.query.OracleXMLQuery to java.lang.String.
    Can somebody tell me a method() for converting to solve my
    problem??????
    Thanks

  • Convert string to datetime and then use in a where clause

    I am trying to pull in warranty expiry dates that have been entered as strings and then perform a calculation as to which ones are expired, about to expire within
    90 days or will expire in more than 90 days. I have got the query to a point where I have converted it to a datetime field (though I'm sure I used the right value to just give me the date, its giving me date and time) and have it printing out the machine name
    and the warranty for that machine.
    SELECT
      machNameTab.machName
      ,convert(date,auditRsltManualFieldValues.fieldValue,103) AS warranty
    FROM
      machNameTab
      INNER JOIN auditRsltManualFieldValues
        ON machNameTab.agentGuid = auditRsltManualFieldValues.agentGuid
    WHERE
      machNameTab.groupName = N'root.company'
      AND auditRsltManualFieldValues.fieldNameFK = 958472722796011
    What I need to do next is change this so instead of just spitting out all the dates as 'Warranty', I want it to give me the fields 'Expired', 'Expiring' (expiry date is within 90 days of the current date) and 90Days (expiry date is over 90 days from the current
    date)

    SELECT
    machNameTab.machName
    ,convert(date,auditRsltManualFieldValues.fieldValue,103) AS warranty,
    select
    case
    when datediff(day,getdate(),convert(date,auditRsltManualFieldValues.fieldValue,103) )<90 then 'Expiring'
    when datediff(day,getdate(),convert(date,auditRsltManualFieldValues.fieldValue,103) )<0 then 'Expired'
    when datediff(day,getdate(),convert(date,auditRsltManualFieldValues.fieldValue,103) )>=90 then '90Days'
    end as status
    FROM
    machNameTab
    INNER JOIN auditRsltManualFieldValues
    ON machNameTab.agentGuid = auditRsltManualFieldValues.agentGuid
    WHERE
    machNameTab.groupName = N'root.company'
    AND auditRsltManualFieldValues.fieldNameFK = 958472722796011
    I added a case to your select. The case will output the strings you wanted based on the date.

  • 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

  • Convert string to datetime produces error

    Hi All,
       I am trying to convert a string to a datetime. When I use the formula below with an alias table, it gives me an error "Invalid Column Name c1.Date"
    SELECT CONVERT(datetime,left([c1.Date],2)'/'substring([c1.Date],3,2)'/'right([c1.Date],4),101) AS Date
    FROM callrecords c1
    Is there another way to convert the string to a datetime?
    I am using CR 2008 SP1.
    Thank you in advance.

    What happen if you run the sql without the conversion,
    SELECT c1.Date FROM callrecords c1
    do you still get the same error message?
    if you don't get the error message you can let crystal do the conversion for you  by using the following function in a formula
    CDate ({c1.Date})

  • Converting string to Datetime?

    Hello all,
    I have seen tons of titles in this forum with the same like mine, but none of them helped solve my issue. It seems very simple, but it gives me a format exception. I am just trying to convert a string to datetime with a specified format.
    string convertToString;
    convertToString = (theWeek.AddDays(i).ToString("dd/MM/yyyy"));
    theDay = DateTime.ParseExact(convertToString, "dd'/'MM'/'yy", null),
    Here theDay is also a DateTime variable.
    These are the errors i get when I execute the code
    1. When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object.
    2. When going into the details of the exception this is what I see " String was not recognized as a valid DateTime".
    Please advise!
    Thanks all.
    Thanks, Sumesh

    Thanks Ante & JayChase for the speedy response.
    I did it the way you mentioned and i was able to get rid of the exception, but still it doesn't show up in the specified format. It shows the time too which I am not asking for. 
    this is what I get now "3/17/2015 12:00:00 AM" .
    I just want 17/03/2015.
    Thanks again.
    Thanks, Sumesh
    I think I see the "problem" here.  I suspect that there isn't one.
    string convertToString;
    convertToString = (DateTime.Now.AddDays(5).ToString("dd/MM/yyyy"));
    DateTime day = DateTime.ParseExact(convertToString, "dd/MM/yyyy", null);
    This works perfectly, as it should.  You appear to have set a breakpoint someplace and you're examining the Visual Studio "value" of the variable 'day.'  You're unhappy that it displays in a manner that you don't like.
    I believe that you're simply not understanding the difference between a System.DateTime object and a System.DateTime represented as a string.
    To start with, a System.DateTime is a 64-bit integer value.  According to the MSDN documentation page:
    Time values are measured in 100-nanosecond units called ticks, and a particular date is the number of ticks since 12:00 midnight, January 1, 0001 A.D. (C.E.) in the
    GregorianCalendar calendar (excluding ticks that would be added by leap seconds). For example, a ticks value of 31241376000000000L
    represents the date, Friday, January 01, 0100 12:00:00 midnight. A DateTime value is always expressed in the context of an explicit or default calendar.
    When you call the DateTime.ToString() method and specify an output style, you get the 64-bit value in the human-readable string representation you want.  When you set a breakpoint and examine the variable in Visual Studio, you get the 64-bit value in
    the human-readable string representation Visual Studio provides by default.
    I hope this helps.
    Content Removed

  • Converting String to datetime format

    I have a String which is in 04-DEC-78 format, I want it to be inserted in to a field in sql database.If I map directly I am getting
    "Microsoft.ServiceModel.Channels.Common.XmlReaderParsingException: The input data for the field/parameter "e_date" is invalid according to the expected SqlDbType DateTime. ---> System.FormatException: The string '04-DEC-65' is not a valid
    AllXsd value.
    Tried to convert the string to datetime format in Mapping but getting error
    public DateTime FormatCheck(string param1)
    IFormatProvider culture = new CultureInfo("en-US", true);
    return  DateTime.ParseExact(param1, "dd/MM/yyyy HH:mm:ss.fff", culture);
    Inline Script Error: The type or namespace name 'CultureInfo' could not be found (are you missing a using directive or an assembly reference?) 
    Help me out!!

    HOLD ON!
    Let's try to clear this up. If the input data is "04-DEC-78" then, sorry, none of the code posted so far will work.
    "04-DEC-78" is not directly parsable so the .ParseExact format must match the source.
    The format for xs:datetime is ISO 8601 which is like yyyy-MM-ddTHH:mm:ss-[offset].  Internally the sqlBinding will cast the XsdDateTime (the .Net xs:datetime implementation) to a SqlDateTime.
    One very, very important missing detail is the type of the SQL parameter.  Is it (SQL) datetime or string?
    If the SQL parameter is datetime, then you can use this:
    public string FormatCheck(string param1)
    return DateTime.ParseExact(param1, "dd-MMM-yy", System.Globalization.CultureInfo.InvariantCulture).ToString("s");

  • Convert String to sql date

    hi all,
    i have a date in string format Tue, 06 Feb 2007 12:38:17 GMT
    How do i convert it to sql datetime.
    Date date = new Date("Tue, 06 Feb 2007 12:38:17 GMT");// creating date
              java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
                        "yyyy-MM-dd HH:mm:ss");// format definition
              java.sql.Time pubDate = java.sql.Time.valueOf(sdf.format(date));
              System.out.println(pubDate);This code gives me java.lang.NumberFormatException.
    Thanks in advance.......
    VikraM

    is "EEE d MMM yyyy HH:mm:ss Z" your default data format
    if not your first constructor will not parse date properly so your date object contains invalid date, when you try to format it it throws exception.
    check it
    sudhir nimavat

  • C# DATETIME to MySql Datetime

    Hi I am looking to convert a c# datetime in this format: 02-11-2015 18:34:32 to a MySQL table using the MySQL DateTime data type. This is the error message I currently get.

    Are you converting the datetime value before submitting it to db?. Try the below code to convert before insert:
    string res = yourdateValue.ToString("MM-dd-yyyy HH:mm:ss");
    Fouad Roumieh

  • Convert String to com.stc.runtime.dt.Date

    Hi every one
    I need to convert a String to com.stc.runtime.dt.Date.
    Can you please guide me?
    thanks.

    String to UtilDate:
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Calendar;
    public class ttest
        private static SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmssZ");
        private static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        public static void main(String[] args) {
         Date dt = null;
         try {
             dt = sdf1.parse("20040921124448+0200");
             System.out.println(dt.toString());
         catch(java.text.ParseException pe) {
             System.err.println("Incorrect Date Format!");
         Calendar cdr = Calendar.getInstance();
         cdr.setTime(dt);
         System.out.println("Year is: " + cdr.get(Calendar.YEAR));
         System.out.println("Zone Offset is: " + cdr.get(Calendar.ZONE_OFFSET));
         Date dt = new Date();
         System.out.println(sdf.format(dt));
         try {
             String sUTC = sdf2.format(dt);
             System.out.println("UTC: " + sUTC);
         catch(IllegalArgumentException pe) {
             System.err.println("Incorrect Date Format 2!");
    }UtilDate and RuntimeDates
    import com.stc.runtime.dt.Date;
    import com.stc.runtime.dt.Time;
    import com.stc.runtime.dt.DateTimeFactory;
    import com.stc.otd.xsd.datatype.Date2001;
    import com.stc.otd.xsd.datatype.Time2001;
    import com.stc.otd.xsd.datatype.DateTime;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    public class dates
        public static void main (String[] parameters)
         dates tq1 = new dates();
         return;
        private dates()
         java.util.Date dtUtil = new java.util.Date();
         Date2001  d2001 = utilDate2xsdDate(dtUtil);
         System.out.println("Current date is: " + d2001.toString());
         com.stc.runtime.dt.Date dt = d2001;
         Time2001 t2001 = utilDate2xsdTime(dtUtil);
         System.out.println("Current time is: " + t2001.toString());
         com.stc.runtime.dt.Time tm = t2001;
         com.stc.runtime.dt.DateTime dttm = new DateTimeFactory().createDateTime();
         //     java.sql.Timestamp dt1 = xsdDateTime2utilTimestamp(new DateTime());
         java.sql.Timestamp dt1 = xsdDateTime2utilTimestamp(dttm);
         System.out.println("Current timestamp is: " +
                      dt1.toString());
         return;
        private java.sql.Timestamp xsdDateTime2utilTimestamp(com.stc.runtime.dt.DateTime dt1)
         Calendar c = dt1.getCal();
         return new java.sql.Timestamp(c.getTime().getTime());
        private Date2001 utilDate2xsdDate(java.util.Date d1) {
         Date2001 dt = new Date2001();
         Calendar c = Calendar.getInstance();
         c.setTime(d1);
         dt.setYear(c.get(Calendar.YEAR));
         dt.setMonth(c.get(Calendar.MONTH) + 1);
         dt.setDay(c.get(Calendar.DAY_OF_MONTH));
         return dt;
        private Time2001 utilDate2xsdTime(java.util.Date d1) {
         Time2001 tm = new Time2001();
         Calendar c = Calendar.getInstance();
         c.setTime(d1);
         tm.setHours(c.get(Calendar.HOUR_OF_DAY));
         tm.setMinutes(c.get(Calendar.MINUTE));
         tm.setSeconds(c.get(Calendar.SECOND));
         return tm;
        private java.util.Date xsdDate2utilDate(Date2001 d1) {
         Calendar c = Calendar.getInstance();
         c.set(d1.getYear(), d1.getMonth() - 1, d1.getDay());
         return c.getTime();
    }

  • Calling a Web Service in a SSRS Report - Error Converting String to Generic List of Strings

    Hello,
    I am using SSRS version 2005 and am trying to call a web service to retrieve data for a SSRS report.  I've looked on Google and MSDN for the past 2 days and have exhausted all options.  Here are the details...
    The web service method I am calling accepts 4 parameters...
    Parameter 1 = Generic list of strings
    Parameter 2 = DateTime
    Parameter 3 = Int
    Parameter 4 = Int
    I have created a function (on the CODE tab in report properties) in my report that gets passed a comma delimited string and returns a Generic List of Strings that I use to format Parameter 1.  The code for the function is as follows:
    Public Function GetIDs(ByVal IDList as String) As List(Of String)
       Dim stringArray() = IDList.Split(",")
       Dim genericList As New List(Of String)(stringArray)
       Return genericList
    End Function
    I am passing a string to the function that looks something like this:
    "1,2,3,4"
    When I try to PREVIEW the report, I get an error that reads:
    "There is an error on line 0 of custom code: [BC30002] Type 'List' is not defined"
    I've tried changing the function declaration to pass back a string array:
    Public Function GetIDs(ByVal IDList as String) As String()
        Return IDList.Split(","c)
    End Function
    This returned the error (from the web service): 
    "Error in line 5 position 22.  Expecting state 'Element'.. Encountered 'Text' with name ", namespace"
    I have also tried changing the function declaration to pass back an array: 
    Public Function GetIDs(ByVal IDList as String) As ARRAY
    This also produced the error:
    "Error in line 5 position 22.  Expecting state 'Element'.. Encountered 'Text' with name ", namespace"
    I know that this particular web service method DOES work because it is coded to accept nulls in the first parameter.  So... when I call the method with nulls, it returns a recordset of ALL data (this works fine).  Only when I pass a string to the function (which "filters" the recordset by the ID list), does the error occur.
    Is SRSS limited with respect to VB.NET code so that the List(Of String) statement is not recognized?  Has anyone done this before and if so, how did you convert a comma delimited string to a Generic List of Strings within a function in the SSRS report?
    Any info would be greatly appreciated.
    Thanks!
    Bob

    Hi Bob,
    By default, in custom code, in order to use a variable or function that is not in the "System" namespace, we need to provide the full name.
    In this case, the full name of the "List" is "System.Collections.Generic.List"
    So, to solve the issue, please use the following code:
    Public Function GetIDs(ByVal IDList as String) As System.Collections.Generic.List(Of String)
    Dim stringArray() = IDList.Split(",")
    Dim genericList As New System.Collections.Generic.List(Of String)(stringArray)
    Return genericList
    End Function
    If you have any more questions, please feel free to ask.
    Thanks,
    Jin Chen
    Jin Chen - MSFT

  • Convert String variable value  to an Object referece type

    Hi all,
    I want to know that if there any possible way to convert String variable value to a Object reference type in java. I'll explain by example if this is not clear.
    Let's think that there is a string variable name like,
    String name="HelloWorld";
    and there is a class name same to the variable value.
    class HelloWorld
    I am passing this string variable value to a method which is going to make a object of helloworld;
    new convertobj().convert("HelloWorld");
    class convertobj{
    public void convert(String name){
    // in hert it is going to create the object of HelloWorld;
    // HelloWorld hello=new HelloWorld(); just like this.
    now i want to do this from the name variable value.( name na=new name()) like wise.
    please let me know if there any possible way to do that.
    I am just passing the name of class by string variable then i wanted to make a instance of the class which come through the variable value.
    thanx.

    Either cast the object to a HelloWorld or use the reflection API (Google it) - with the reflection API you can discover what methods are available.
    Note: if you are planning to pass in various string arguments and instantiate a class which you expect to have a certain method... you should define an interface and have all of your classes that you will call in this way implement the interface (that way you're sure the class has a method of that name). You can then just cast the object to the interface type and call the method.
    John

Maybe you are looking for

  • How to apply the Patchset 7 to Forms 6i

    Hi all !!! I need install the PatchSet 7 in the iAS Server 1.0.2.2.2 (concrectly at the Forms Server Service). I had stopped all services of Oracle, and had applied the patch. But the services of Forms and Reports is missing after. Any idea. How to a

  • Use more than 2 GB ram for oracle

    I have 16 GB ram but I only can use 2 GB of that for oracle database , how can i increase that ???

  • Online Database for Students?

    I am attempting to take a class on Oracle. Problem is my computer is down at home. Is there an online location that has an Oracle Database that I could use to create my own little database. It will be nothing much just a few small tables for queries

  • Pages changes the page size when exporting to pdf

    When exporting a pages document (size 8.5w x 7.0h) to pdf it changes the size to (8.5w x 11.0h) any suggestions on exporting it correctly. If not is there a way to resize it once it is a pdf or other software to convert it correctly? I am using Pages

  • External Multi Way Merge Sort in Java!

    Hi guys, some month ago I've sent [this post|http://forums.sun.com/thread.jspa?forumID=31&threadID=5310310] to the Java Programming Forum to notify the availability of an External Multi Way Merge Sort written in Java, tuned and tested over GB of text