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

Similar Messages

  • 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

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

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

  • Unable Update SQL Developer with Times Ten in-Memory DB Extension 1.2.1.1.0

    SQL Developer 1.2.1 Build MAIN 32.13 (Windows XP)
    We can't Update SQL Developer with Times Ten in-Memory DB Extension 1.2.1.1.0 :-((
    We did the same actions as described in tutorial
    http://www.oracle.com/technology/products/timesten/viewlets/tt703_sqldev_install_ext_viewlet_swf.html
    In addition to tutorial we have "Log In" window
    "To download Oracle Times Ten in-Memory Database Extension
    you must enter your Oracle Web Account user name and password"
    This window was not displayed in tutorial...
    We try to use three our OTN accounts and the result
    was the same - we was asked with "User name" and "Password"
    again, again, again and again,,, :-(
    Is it a bug or a feature?
    Mayby we didn't understand something or did something wrong?

    Hi Simon,
    I found cause of update failure! It was the HTTP proxy setting.
    I turned off "Use HTTP proxy server" checkbox in SQL Developer -> Tools -> Preferences -> Web Browser and Proxy.
    After this action SQL Developer was successfully updated with Times Ten Extension.
    Valery Yourinsky

  • Any instance of time being displayed through Firefox is 5 hours off (+) (IE Comcast call time logs, every page print out, etc). IE and all other browers display correctly as is all of the time settings on my computer. Please help.

    Any instance of time being displayed when using Firefox show the time off by +5 hours. I am in Phila so use EST. Every other setting is correct in computer. For example time call log displayed from Comcast and every page footer shows time +5 hours. I have not found anything helpful in searching the web. I always check after each upgrade to Firefox but problem persists.

    Cor-el... The issue was in the autoexec.bat file. I did have the TZ set there. Removed and all is well.
    Thanks Much.
    -Bill

  • Converting Oracle query to Sql Server with date manipulation

    The following SSIS statement works great in Oracle, and it parses successfully in the "Sql Task" window. In Oracle it returns
    this result:
    FROM_DT              THRU_DT
    16-Jan-2014      23-Jan-2014
    select
    case
    when to_char(to_date(sysdate,'dd-mon-yyyy'),'dd') <=7 then to_date('24'||to_char(add_months(sysdate,-1),'mmyyyy'),'ddmmyyyy')
    when to_char(to_date(sysdate,'dd-mon-yyyy'),'dd') <=15 then to_date('01'||to_char(sysdate,'mmyyyy'),'ddmmyyyy')
    when to_char(to_date(sysdate,'dd-mon-yyyy'),'dd') <=23 then to_date('08'||to_char(sysdate,'mmyyyy'),'ddmmyyyy')
    else to_date('16'||to_char(sysdate,'mmyyyy'),'ddmmyyyy')
    end as from_dt,
    case
    when to_char(to_date(sysdate,'dd-mon-yyyy'),'dd') <=7 then trunc(last_day(add_months(sysdate,-1)))
    when to_char(to_date(sysdate,'dd-mon-yyyy'),'dd') <=15 then to_date('07'||to_char(sysdate,'mmyyyy'),'ddmmyyyy')
    when to_char(to_date(sysdate,'dd-mon-yyyy'),'dd') <=23 then to_date('15'||to_char(sysdate,'mmyyyy'),'ddmmyyyy')
    else to_date('23'||to_char(sysdate,'mmyyyy'),'ddmmyyyy')
    end as thru_dt
    from sys.dual
    How can I convert this to Sql Server ?

    >>You mean you get the data from Oracle and tries to insert it into SQL Server?
    - no, sorry, I want to convert the syntax to Sql Server
    >>Are
    you running the query in OLEDB provider connected to the Oracle's database?
    - yes, this works fine now (after fixing this redundancy:
    to_char(to_date(sysdate,'dd-mon-yyyy'),'dd')change toto_char(sysdate,'dd')

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

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

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

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

  • 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

Maybe you are looking for

  • Microsoft Word 2011 crash after preview

    I have a problem with Microsoft Word 2011. When I push the button for the preview I have a black screen and after the software crash. I have the following report. I'm sorry for my bad english. Process:         Microsoft Error Reporting [1479] Path:  

  • Create folder in current directory

    Hi all, I would like to be able to create a folder through my java program, in the current directory that the java program is in. Furthermore, I do not want to have to change any code if the java program is suddenly moved to a different folder. Somet

  • X11 fails to start after Security Update 2010-002

    I installed Security Update 2010-002 and QuickTime 7.6.6, and now X11 fails with a dylib problem: Dyld Error Message: Library not loaded: /usr/X11/lib/libpixman-1.0.dylib Referenced from: /Applications/Utilities/X11.app/Contents/MacOS/X11.bin Reason:

  • DEBUGGING PACKAGES

    Hi, I am new to SQL developer having moved from using TOAD. I am having difficulty debugging procedures within packages. On the left hand side there is a tree structure i select packages, open the package body and set a break point. I then compile fo

  • Anyone know how to convert .FLV to iMovie or FinalCut Pro?

    I downloaded a video with file extension .FLV I wanted to convert this to either .MOV or .MP4 Know any apps I can use to do this? I need the video inserted in a Keynote file. Thanks!